jdbc连接数据库进行增删改
连接数据库的三个步骤
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接对象(地址,用户名,密码)
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/manage", "root", "root");
//使用Statement接口获取SQL语句
Statement st =conn.createStatement();
1、添加数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Demo02 {
public static void main(String[] args) throws Exception {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接对象(地址,用户名,密码)
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/manage", "root", "root");
String sql = "insert into student values(null,'狗子',10,'男')";
//使用Statement接口获取SQL语句
Statement st =conn.createStatement();
int count = st.executeUpdate(sql);
if (count>0) {
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
st.close();
conn.close();
}
}
2、修改数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Demo03 {
public static void main(String[] args) throws Exception {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接对象(地址,用户名,密码)
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/manage", "root", "root");
//定义sql
String sql = "update student set age = 200 where name = '狗子'";
//获取执行sql对象
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println( st);
if ( count>0) {
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
st.close();
conn.close();
}
}
3、删除数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Demo4 {
public static void main(String[] args) throws Exception {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接对象(地址,用户名,密码)
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/manage", "root", "root");
String sql = "delete from student where name = '狗子'";
//使用Statement接口获取SQL语句
Statement st =conn.createStatement();
int count = st.executeUpdate(sql);
if (count>0) {
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
st.close();
conn.close();
}
}
结论
由上面jdbc连接数据库使用Statement接口获的方法取sql语句,无论增删改只需要改sql语句命令即可,这里的异常我知道自己的账号密码和数据表名及列的顺序所以选择直接抛出便于对比