java mysql plus

本文通过一个Java程序演示了如何使用JDBC连接MySQL数据库并执行增删改查操作。具体包括插入一条记录、删除指定ID的记录、更新指定ID的记录信息以及查询所有记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class helloworld {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata?useUnicode=true&characterEncoding=utf-8", "root", "");
		System.out.println(con);
		
		
		String sql_in = "insert into student values(null, ?, ?)";
		PreparedStatement pst_in = con.prepareStatement(sql_in);
		pst_in.setString(1, "灑錒魤");
		pst_in.setInt(2, 56);
		int exi = pst_in.executeUpdate();
		if(exi == 1) System.out.println("insert success");
		
		
		String sql_de = "delete from student where id=?";
		PreparedStatement pst_de = con.prepareStatement(sql_de);
		pst_de.setInt(1, 13);
		int exd = pst_de.executeUpdate();
		if(exd == 1) System.out.println("delete success");
		
		
		String sql_ud = "update student set name=?,age=? where id=?";
		PreparedStatement pst_ud = con.prepareStatement(sql_ud);
		pst_ud.setString(1, "xiaohong");
		pst_ud.setInt(2, 99);
		pst_ud.setInt(3, 8);
		int exu = pst_ud.executeUpdate();
		if(exu == 1) System.out.println("update success");
		
		String sql = "select * from student";
		PreparedStatement pst = con.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();
		while(rs.next())
		{
			int id = rs.getInt(1);
			String name = rs.getString(2);
			int age = rs.getInt(3);
			System.out.printf("%d %s %d\n", id, name, age);
		}
		rs.close();
		pst.close();
		con.close();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值