写在前面:
1.MySQL数据库的jdbc驱动名:" com.mysql.jdbc.Driver "
2.本地数据库url:" jdbc:mysql://localhost:3306/wangqihao "
(3306/后面写本地数据库名称)
一、访问数据库六步(或五步):
1.加载驱动
2.创建连接
3.创建数据库操作对象(Statement对象)
4.执行SQL语句 (使用Statement接口中的三个方法)
5.处理返回结果集 //这一步在数据库查询时用,只增删改时省略此步
6.释放资源
二、数据库操作代码框架 :
import java.sql.*;
public class JDBCtest01 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
//ResultSet rs = null;(查询表时使用)
String url = "xxx";
String user = "xxx";
String passwd = "xxx";
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建数据库连接
conn = DriverManager.getConnection(url,user,passwd);
//3.创建数据库操作对象
stmt = conn.createStatement();
//4.执行sql语句
int count = stmt.executeUpdate("xxx ");
System.out.print("插入/删除/更新"+count+"条成功!");
}catch(Exception e) {
e.printStackTrace();
}finally {
//6.释放资源
try {
/*
if(rs!=null) {
rs.close();
}
(查询操作时使用)
*/
if(stmt!=null) {
stmt.close();
}
if(conn!=null) {
conn.close();
}
} catch (SQLException e2) {
}
}
}
}
三、“增删改”操作具体实例
1.数据库插入数据(insert)
import java.sql.*;
public class JDBCtest01 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/wangqihao";
String user = "root";
String passwd = "0419";
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建数据库连接
conn = DriverManager.getConnection(url,user,passwd);
//3.创建数据库操作对象
stmt = conn.createStatement();
//4.执行sql语句
int count = stmt.executeUpdate("insert into emp(ename,age,job) values('张三',20,'经理') ");
System.out.print("插入"+count+"条成功!");
}catch(Exception e) {
e.printStackTrace();
}
finally {
//6.释放资源
try {
if(rs!=null) {
rs.close();
}
if(stmt!=null) {
stmt.close();
}
if(conn!=null) {
conn.close();
}
} catch (SQLException e2) {
// TODO: handle exception
}
}
}
}
我们打开Navicat查看一下:
数据插入成功!
删除(delet)和修改(update)代码大体与上面相同
同样都是使用 stmt.excuteUpdate(“deletSQL/updateSQL”) 方法
只需要改变括号中的SQL语句即可完成操作。