用java对mysql进行操作

增、删、改操作

第一步:导jar包

链接: https://pan.baidu.com/s/1LktlCZmdSO428MIfWji_aw 提取码: xh6x

第二步:创建驱动类

Class.forName("com.mysql.jdbc.Driver");

第三步:创建连接

  1. String url = "jdbc:mysql://localhost:3306/mydb1"(jdbc:工商名称:主机:端口号/数据库名称)
  2. String username = "root";(数据库用户名)
  3. String password = "123";(数据库密码)
  4. Connection con = (Connection) DriverManager.getConnection(url, username, password);

第四步:创建statement

Statement sta = con.createStatement();

第六步:写出增、删、改的sql语句

String sql = "delete from stu where number='ITCAST_0004'";

第七步:执行sql语句

int r = sta.executeUpdate(sql);

查操作

        //创建驱动类
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/mydb1";
		//通过剩下的三个参数调用DriverManger的getConnection(),得到连接
		Connection con = (Connection) DriverManager.getConnection(url, "root", "123");
		//得到Statement
		Statement sta = con.createStatement();
		String sql = "SELECT * from stu";
	    //得到表,即结果集
		ResultSet rs = sta.executeQuery(sql);

对ResultSet的介绍

对ResultSet操作的具体代码:

        /*
		 * 解析ResultSet对象
		 * 1、把行光标移动到第一行,可以调用next方法
		 */
		while(rs.next()) {
			String number = rs.getString(1);
		    String name = rs.getString("name");
		    int age = rs.getInt(3);
		    String gender = rs.getString("gender");
		    System.out.println(number+","+name+","+age+","+gender);
		    //将这三个关掉,否则后期频繁使用会消耗内存
		    rs.close();
		    sta.close();
		    con.close();

猜你喜欢

转载自blog.csdn.net/hello_sherry_1028/article/details/83243181