java实现jdbc连接数据库进行增删改的操作

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语句命令即可,这里的异常我知道自己的账号密码和数据表名及列的顺序所以选择直接抛出便于对比

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值