jdbc连接SQL server的步骤:
-
加载驱动
driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; Class.forName(driver); -
建立连接
url ="jdbc:sqlserver://localhost:1433;DatabaseName=StudentDB"; name = "sa"; pwd = "sa123456"; Connection con = DriverManager.getConnection(url, name, pwd) -
创建执行sql的语句(Statement)
Statement st=con.createStatement(); st.executeQuery(sql); String sql="select * from Student where Sno=?"; PreparedStatement ps=con.prepareStatement(sql); ps.setString(1,"1"); ps.executeQuery(); -
执行并处理结果(ResultSet)驱动,class.forName()
ResultSet rs=statement.executeQuery(sql); while(rs.next()){ rs.getString("Sno") } -
释放资源 Connection非常占用资源,使用后必须马上释放;
rs.close();pst.close(); con.close();
package shop.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
private String url = "jdbc:sqlserver://localhost:1433;DatabaseName=PetShop";// 数据连接字符串
private String name = "sa";//数据库用户名
private String pwd = "123123";//密码
public Connection con;
public PreparedStatement pst;
public ResultSet rs;
public Connection getCon() {
//连接数据库
try {
//1.加载jdbc驱动.class.forName()
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//2.与数据库创建连接Connection con=DriverManager.getConnection(数据连接字符串,数据库用户名,密码)
con = DriverManager.getConnection(url, name, pwd);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public ResultSet Select(String sql, Object[] ps) {
if (con == null) {
con = getCon();
}
try {
//3.发送sql语句
pst = con.prepareStatement(sql);
if (ps != null)
for (int i = 0; i < ps.length; i++) {
pst.setObject(i + 1, ps[i]);
}
rs = pst.executeQuery();
return rs;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return rs;
}
}
public boolean executeUpdate(String sql, Object[] ps) {
if (con == null) {
con = getCon();
}
try {
pst = con.prepareStatement(sql);
for (int i = 0; i < ps.length; i++) {
pst.setObject(i + 1, ps[i]);
}
int i = pst.executeUpdate();
return i > 0 ? true : false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} finally {
Close();
}
}
public void Close() {
try {
if (rs != null)
rs.close();
if (pst != null)
pst.close();
if (con != null)
con.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
```



被折叠的 条评论
为什么被折叠?



