创建数据库mydb
新建查询
CREATE TABLE `t_user` (
`uid` int(8) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NULL DEFAULT NULL,
PRIMARY KEY (`uid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 ROW_FORMAT = Dynamic;
写好配置文件 druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost\:3306/mydb?useUnicode\=true&characterEncoding\=utf-8
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000
导入jar包 :
- druid-1.0.9.jar
- mysql-connector-java-5.1.37-bin.jar
链接:https://pan.baidu.com/s/13yhG_qBIu0pi_4GXK5o9Zg
提取码:v38y
写工具类JDBCUtils JDBCUtils.java
package com.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class JDBCUtils {
// 1.声明静态数据源成员变量
private static DataSource ds;
// 2.创建连接池对象
static {
// 加载配置文件中的数据
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
Properties pp = new Properties();
try {
pp.load(is);
// 创建连接池,使用配置文件中的参数
ds = DruidDataSourceFactory.createDataSource(pp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 3.定义公有的得到数据源的方法
public static DataSource getDataSource() {
return ds;
}
// 4.定义得到连接对象的方法
public static Connection gerConnection() throws SQLException {
return ds.getConnection();
}
// 5.定义关闭资源的方法
public static void close(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 6.重载关闭方法
public static void close(Connection conn, Statement stmt) {
close(conn, stmt, null);
}
//测试 插入操作
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
// 1.获取连接
try {
conn = JDBCUtils.gerConnection();
//2.定义sql
String sql = "insert into t_user values(null,?,?,?)";
//3.获取pstmt对象
pstmt = conn.prepareStatement(sql);
//4.给?赋值
pstmt.setString(1, "张三");
pstmt.setString(2, "123456");
pstmt.setString(3, "111@qq.com");
//5.执行sql
int count = pstmt.executeUpdate();
System.out.println(count);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//6.释放资源
JDBCUtils.close(conn, pstmt);
}
}
}