JDBC:增、删、改、查

package database;
import java.sql.*;

public class Crud {

	public static void main(String[] args) {
        Connection conn = null;
		PreparedStatement ps = null;
		ResultSet res = null;

		//1、注册JDBC驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		try {
			//2、建立连接
			conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/student", "root", "123456");

			//3、创建PreparedStatement对象
			ps =  conn.prepareStatement("select CNO,CNAME,CTEACHER from c where cteacher = ? ;");
			ps.setString(1, "张");	
			
			//4、执行查询结果
			res = ps.executeQuery();

			//5、循环读出
			while(res.next())
			{
				System.out.println(res.getInt("CNO")+" "+res.getString("cname")+" "+res.getString("cteacher"));
			}
			
			//6、向表c中插入一条记录
			ps = conn.prepareStatement("insert into c(cno,cname,cteacher) values(?,?,?);");
			ps.setInt(1, 6);
			ps.setString(2, "化学");
			ps.setString(3, "王志宇");
			int mark = ps.executeUpdate();
			System.out.println("mark: "+mark);
			
			//7、更新数据
			ps = conn.prepareStatement("update c set cteacher = ? where cname = ?;");
			ps.setString(1, "张雪如");
			ps.setString(2, "政治");
			int mark1 = ps.executeUpdate();
			System.out.println("mark1: "+mark1);
			
			//8、删除数据/记录
			ps = conn.prepareStatement("delete from c where cno = ?;");
			ps.setInt(1, 6);
			int mark2 = ps.executeUpdate();
			System.out.println("mark2: "+mark2);
			

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			// 关闭资源

			try {
				if(res != null)
				{
					res.close();
				}
				if(ps != null)
				{
					ps.close();
				}
				if(conn != null)
				{
					conn.close();
				}

			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_24369689/article/details/83719326