Java 数据库编程「 备考篇 1」

2023-03-09 19:03:37 浏览数 (1)

说明:仅仅用于复习。

代码语言:javascript复制
package aaa;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main{
	public static void main(String[] args){
		Connection con = DBConn.getCon(); // 这里DBConn假设我们已经写好连接部分,就直接操作了
		//  现在假装表的名字叫 student 表中有 id name age
		String sqlInsert1 = "insert into student values('ME,20')"; // 将name = ME age = 20 的插入到表中
		String sqlInsert2 = "insert into student values('CHY,19')";
		String sqlUpdate = "update student  set age = 22 where id = 2"; // 将 student 中 id = 2 的 age 重新 set 为 22
		String sqlDelete = "delete from student";  // 删除操作
		String sqlSelect = "select * from student";  // 挑选 
		
		Statement st = con.createStatement();
		st.executeUpdate(sqlInsert1);
		st.execute(sqlInsert2);
		st.execute(sqlUpdate);
		st.executeUpdate(sqlDelete);
		ResultSet  rs = st.executeQuery(sqlSelect);
		while(rs.next()){
			System.out.println(rs.getInt(1)   " "   rs.getString(2)   " "   rs.getInt(3));  //四种输出方法
			System.out.println(rs.getInt("id")   " "   rs.getString("name")   rs.getInt("age"));
			System.out.println(rs.getString("id")   " "   rs.getString("name")   rs.getString("age"));
			System.out.println(rs.getString(1)   " "   rs.getString(2)   rs.getInt(3));
		}
	}
}

0 人点赞