【www.hzclsc.cn--热门资讯】
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. Class.forName( com.microsoft.sqlserver.jdbc.SQLServerDriver 获取到对应于你要使用的数据库的 连接插件 (驱动),有这个驱动你才能用java来连接SQL server。对应的,如果你用MySQL的话,那么这个驱动就变成了 com.mysql.jdbc.Driver 了。
2. DriverManager.getConnection( jdbc:sqlserver://localhost:1433;databasename=HcitPos , sa , 123 通过jdbc:sqlserver:里面的sqlserver来寻找需要的驱动,如果需要的驱动已经在上面的Class.forName中注册了,那就行啦,直接返回一个到数据库的连接给你了。如果没有找到需要的驱动,呃,那就抛出异常~~相对应于MySQL的,也给你个例子对比好了:DriverManager.getConnection( jdbc:mysql://localhost/HcitPos , sa , 123 )。
3.conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);获得一个Statement对象,为什么要搞一个对象对来而不是直接就查询呢?这是因为一个Statement对象只能为你保存一个结果集ResultSet,所以如果你有多个结果集需要零时保存着的,那么就用Statement对象。如果你不需要的话,而且想要程序执行的效率高一点的话,那么用prepareStatement吧。
本文来源:http://www.hzclsc.cn/news/35393.html