//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送SQL的对象Statement,PreparedStatement : CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql = "select * from users";
//5.执行查询SQL,返回一个 ResultSet : 结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//6.关闭连接,释放资源(一定要做) 先开后关
rs.close();
statement.close();
connection.close();
预编译Sql
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写SQL
String sql = "insert into users(id, name, password, email, birthday) values (?,?,?,?,?);";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,5);//给第一个占位符? 的值赋值为1;
preparedStatement.setString(2,"学习Java");//给第二个占位符? 的值赋值为狂神说Java;
preparedStatement.setString(3,"123456");//给第三个占位符? 的值赋值为123456;
preparedStatement.setString(4,"24736743@qq.com");//给第四个占位符? 的值赋值为1;
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符? 的值赋值为new Date(new java.util.Date().getTime());
//5.执行SQL
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("插入成功@");
}
//6.关闭连接,释放资源(一定要做) 先开后关
preparedStatement.close();
connection.close();
开启事务
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection connection = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务,false 开启
connection.setAutoCommit(false);
String sql = "update account set money = money-100 where name = 'A'";
connection.prepareStatement(sql).executeUpdate();
//制造错误
//int i = 1/0;
String sql2 = "update account set money = money+100 where name = 'B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上两条SQL都执行成功了,就提交事务!
System.out.println("success");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JdbcUtis工具类
//操作数据库的公共类
public class JdbcUtis{
private static String driver;
private static String url;
private static String user;
private static String password;
//静态代码块,在类加载的时候执行
static{
//读取配置文件
//1、创建properties对象
Properties properties = new Properties();
//2、通过类加载器加载资源文件为字节输入流
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
}
/**
* 获取数据库连接
* @return
*/
public static Connection getConnection(){
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
//2、编写查询公共方法 —— 注意查询的结果返回为ResultSet结果集
/**
* 用于查询数据的公共方法,注意:使用发送SQL语句的对象为PreparedStatement
* @param sql:查询的sql语句,由前端传递
* @param params:sql语句中占位符的值
*
*===============这下面的3个参数之所以在调用的时候传递原因就在于这3个都是资源,我们需要关闭,如果我们直接在这个方法里获取资源对象的话,那么我们就应该在这个方法中关闭资源===============
*===============但是调用处还在等待这个方法返回结果集,所以我们不应该在这个地方获取这3个对象,而应该由调用出传递,这样可以统一管理和关闭资源===============
*
* @param connection:调用出使用BaseDao.getConnection()获取到数据库连接对象传入
* @param pstm:调用出只是传入null的引用。这个对象真正的实例化放在这个方法里面
* @param rs:返回的结果集,和pstmt只是传入null的引用。这个对象真正的实例化放在这个方法里面
*
* @return:返回查询到的结果集
*/
public static ResultSet execute(Connection connection,PreparedStatement pstm,ResultSet rs,
String sql,Object[] params) throws Exception{
pstm = connection.prepareStatement(sql);
for(int i = 0; i < params.length; i++){
pstm.setObject(i+1, params[i]);
}
rs = pstm.executeQuery();
return rs;
}
//3、编写修改公共方法
/**
* 用于修改数据的公共方法,注意:使用发送SQL语句的对象为PreparedStatement
* @param sql:修改数据的sql语句模板
* @param params:模板中占位符对应的值
*
* =====下面两个对象需要调用出传入也是为了统一管理和关闭资源=====
* @param connection:调用出使用BaseDao.getConnection()获取到数据库连接对象传入
* @param pstm:调用出只是传入null的引用。这个对象真正的实例化放在这个方法里面
*
* @return 返回受影响的行数
*/
public static int execute(Connection connection,PreparedStatement pstm,
String sql,Object[] params) throws Exception{
int updateRows = 0;
pstm = connection.prepareStatement(sql);
for(int i = 0; i < params.length; i++){
pstm.setObject(i+1, params[i]);
}
updateRows = pstm.executeUpdate();
return updateRows;
}
//4、编写关闭资源公共方法
/**
* 关闭资源
* @param connection:调用出使用BaseDao.getConnection()获取到数据库连接对象传入
* @param pstm:调用出只是传入null的引用。这个对象真正的实例化放在这个方法里面
* @param rs:返回的结果集,和pstmt只是传入null的引用。这个对象真正的实例化放在这个方法里面
* @return:返回关闭资源的结果
*
* 注意:关闭资源的时候要倒着关
*/
public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet rs){
boolean flag = true;
if(rs != null){
try {
rs.close();
rs = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
if(pstm != null){
try {
pstm.close();
pstm = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
if(connection != null){
try {
connection.close();
connection = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
return flag;
}
}