JDBC学习
package Demo_01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 对应数据库中对demo表的所有操作
* insert
* update
* delete
* select
* 如果还有其他的表,再创建一个类似的表明Dao的类
* xxxxDao 该类专门进行对应表的sql语句操作
* (1) 三个准备
* ① 数据库
* 1) 注意编码格式 utf8
* 2) 创建表(是否需要修改引擎),采用合理的表结构存放数据
* ② 添加数据库的驱动jar文件到项目中,自己创建一个lib目录进行存放
* ③ 把jar文件添加到类路径中
* (2) 七个步骤
*/
public class BookdemoDao {
public static void main(String[] args) {
BookdemoDao bookDao = new BookdemoDao();
String sql = "insert into demo_01(b_no, b_name, b_price)\n" +
"values('124','特朗普',250)";
int r = bookDao.executeUpdate(sql);
if(r > 0){
System.out.println("成功");
}else {
System.out.println("失败");
}
}
public int executeUpdate(String sql){
int r = 0;//第一步,声明数据库连接所需要的参数
String drive = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/jdbc_demo?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String password = "123456";
Connection conn = null;
Statement stat = null;
try {//第二步,加载驱动类,需要处理异常
Class.forName(drive);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {//第四步,在主函数编写sql语句,
conn = DriverManager.getConnection(url,user,password);//创建一个执行sql语句的对象,把sql语句发送给数据库DBMS并获取结果
stat = conn.createStatement();
r = stat.executeUpdate(sql);//第六步,执行sql语句并处理结果
} catch (SQLException e) {
e.printStackTrace();
}finally {//关闭资源
if(stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
stat = null;
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
conn = null;
}
}
}
return r;
}
}