用java怎样把数据存到数据库中

2024年11月17日 08:23
有4个网友回答
网友(1):

只能写个大概的,要写数据到数据库中,先得在数据库中建库,库里建表,表里建字段,然后java里建立数据库连接,用SQL语言写数据到表中的字段
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
//String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=数据库名"; //7.0、2000
String url="jdbc:sqlserver://localhost:1433;DatabaseName=数据库名"; //2005
Connection conn=null;
conn= DriverManager.getConnection(url,用户名,密码);
PreparedStatement pst=null;
pst=conn.prepareStatement("Insert Into grade(表名) Values (?)");
pst.setInt(1,你要写的整弄数据);
//pst.setString(2,你要写的字符串数据);
pst.addBatch();
pst.executeBatch();

网友(2):

jdbc连接数据库,执行sql语句

网友(3):

1.提取单条记录
//import java.sql.*;
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:%%1";
con=DriverManager.getConnection(url,%%2,%%3);
stmt=conn.createStatement();
stmt.executeUpdate(%%4);
rs=stmt.executeQuery(%%5);
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

3.显示表格
/*
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import javax.swing.table.*;
*/
String[] colHeads=%%4;
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:%%1";
conn=DriverManager.getConnection(url,%%2,%%3);
stmt=conn.createStatement();
rs=stmt.executeQuery("SELECT count(*) as au_count from "+%%5);
rs.next();
int iCount=rs.getInt("au_count");
Object[][] data=new Object[iCount][];
int i=0;
rs=stmt.executeQuery("SELECT * from "+%%5);
while(rs.next()){
data[i]=new Object[iCount];
data[i][0]=rs.getString("au_fname");
data[i][1]=rs.getString("Phone");
data[i][2]=rs.getString("City");
i++;
}
JTable table=new JTable(data,colHeads);
JScrollPane jsp=new JScrollPane(table);
getContentPane().add(jsp);
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
6.关闭时关闭连接
//import java.sql.*;
addWindowListener(new WindowAdapter{
public void windowClosing(WindowEvent wevent){
if(stmt!=null){
try {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

7.执行命令
//import java.sql.*;
Connection conn=null;
PreparedStatement pst=null;
try {
conn=DriverManager.getConnection(url);
pst=conn.prepareStatement("Insert Into grade(%%1) Values (?)");
pst.setInt(1,%%2);
//pst.setString(2,%%2);
pst.addBatch();
pst.executeBatch();
} catch (SQLException e){
e.printStackTrace();
}
finally{
try {
if (pst != null)
pst.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

网友(4):

嗯 用jdbc 或者orm框架 hibernate之类的