Java如何与数据库连接
- 提问者网友:十年饮冰
- 2021-04-22 09:10
- 五星知识达人网友:怀裏藏嬌
- 2021-04-22 09:53
import java.sql.*;
public class DBConnect {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
private PreparedStatement ps = null;
public DBConnect()
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databasename=HcitPos", "sa", "123");
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
}
catch (SQLException ex)
{
System.out.println(ex.getMessage() + "路径错误");
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage() + "驱动错误");
}
}
public PreparedStatement getPs(String sql) throws SQLException {
try {
ps = conn.prepareStatement(sql);
conn.commit();
return ps;
} catch (Exception e) {
//conn.rollback();
e.printStackTrace();
return ps;
}
}
public ResultSet executeQuery(String ssql) throws SQLException{
try{
rs = stmt.executeQuery(ssql);
return rs;
}
catch(SQLException se){
//conn.rollback();
System.out.println("DBBean.executeQuery() ERROR:"+se.getMessage());
}
return rs;
}
public int executeUpdate(String ssql) throws SQLException{
int iupdate = 0;
try{
iupdate = stmt.executeUpdate(ssql);
return iupdate;
}
catch(SQLException se){
//conn.rollback();
System.out.println("DBBean.executeUpdate() ERROR:"+se.getMessage());
}
return iupdate;
}
public void free() throws SQLException{
try{
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}
catch(SQLException se){
System.out.println("DBBean.free() ERROR:"+se.getMessage());
}
}
public Connection getConnection() {
return conn;
}
}
- 1楼网友:千杯敬自由
- 2021-04-22 11:10
1. 加载驱动
2。取得连接
3。创建Statement
4. 执行SQL语句
5。返回ResultSet
- 2楼网友:鸠书
- 2021-04-22 11:00
import java.sql.*;
public class CreateStudent {
public static void main(String args[]) { String url="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\Access2003\\db2.mdb";
String sql = "create table teacher"+ " (name VARCHAr(20), " + " sex CHAr(2), " + " birthday Date, " + " leave BIT, " + " stnumber INTEGER);";
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }catch(java.lang.ClassNotFoundException e) { System.out.println(1); } try { Connection con = DriverManager.getConnection(url); Statement stmt = con.createStatement(); try { stmt.executeUpdate(sql); System.out.println("teacher table created"); }catch(Exception e) { System.out.println(2); } stmt.close(); con.close(); }catch(SQLException e) { System.out.println(3); } } }