Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/数据库", "用户名", "密码");
PreparedStatement state = con.prepareStatement("sql语句");
state.setXxx(占位符 , 付得值);
ResultSet rs = state.executeQuery();/或者 int i = state.executeUpdate();--执行几行数据
while (rs.next()) {
rs.getXxx();
}
state.close();
con.close();
rs.close();
/**
* Druid连接池的工具类
*/
public class JDBCUtils {
//1.定义成员变量 DataSource
private static DataSource ds ;
static{
try {
//1.加载配置文件
Properties pro = new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//2.获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 释放资源
*/
public static void close(Statement stmt,Connection conn){
/* if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}*/
close(null,stmt,conn);
}
public static void close(ResultSet rs , Statement stmt, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 获取连接池方法
*/
public static DataSource getDataSource(){
return ds;
}
}
where.jpg (37.58 KB, 下载次数: 22)
多对多.jpg (66.55 KB, 下载次数: 20)
内外连接的区别.jpg (110.31 KB, 下载次数: 25)
一对多.jpg (72.29 KB, 下载次数: 53)
一对一.jpg (106.13 KB, 下载次数: 18)
937 Bytes, 下载次数: 108
1.58 KB, 下载次数: 103
3.81 KB, 下载次数: 106
5.02 KB, 下载次数: 120
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |