时间:2021-07-01 10:21:17 帮助过:3人阅读
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
public class DemoPreparedstement {
	public static void testselect(int cno) throws Exception {
		DriverManager.registerDriver(new Driver());
		// Class.forName("com.mysql.jdbc.Driver");
		// 2.获取连接对象
		String url = "jdbc:mysql://localhost:3306/a";
		Connection conn = DriverManager.getConnection(url, "root", "cjx990725");
		// 3.获取载体
		PreparedStatement pstmt = conn.prepareStatement("select * from coure where cno=?");
		// 给?设置值,从左到右赋值,序号从1开始,
		pstmt.setInt(1, cno);
		// 执行
		ResultSet rs = pstmt.executeQuery();//执行操作
		if (rs.next()) {
			int id = rs.getInt(1);
			String name = rs.getString(2);
			int cpno = rs.getInt(3);
			int ss = rs.getInt(4);
			System.out.println(id + "  " + name + "  " + cpno + "  " + ss);
		}
}
	public static void update(int cno,String cname) throws SQLException{
		DriverManager.registerDriver(new Driver());
		String url="jdbc:mysql://localhost:3306/a";
		Connection conn=DriverManager.getConnection(url, "root", "cjx990725");
		System.out.println(conn);
		PreparedStatement pstmt = conn.prepareStatement("update coure set cname=? where cno=?");
		pstmt.setString(1, cname);
		pstmt.setInt(2, cno);
		int n= pstmt.executeUpdate();//返回int类型
		System.out.println(n);
		pstmt.close();
		conn.close();
	}
	public static void delete(int cno) throws SQLException{
		DriverManager.registerDriver(new Driver());
		String url="jdbc:mysql://localhost:3306/a";
		Connection conn=DriverManager.getConnection(url, "root", "cjx990725");
		System.out.println(conn);
		PreparedStatement pstmt = conn.prepareStatement("delete from coure where cno=?");
		pstmt.setInt(1, cno);
		int n= pstmt.executeUpdate();
		System.out.println(n);
		pstmt.close();
		conn.close();
	}
	public static void insert(String cname,int cpno,int ccredit,int cno) throws SQLException{
		DriverManager.registerDriver(new Driver());
		String url="jdbc:mysql://localhost:3306/a";
		Connection conn=DriverManager.getConnection(url, "root", "cjx990725");
		PreparedStatement pstmt = conn.prepareStatement("insert into coure(cno,cname,cpno,ccredit) values(?,?,?,?)");
		pstmt.setString(2, cname);
		pstmt.setInt(3, cpno);
		pstmt.setInt(4, ccredit);
		pstmt.setInt(1, cno);
		int n= pstmt.executeUpdate();
		System.out.println(n);
		pstmt.close();
		conn.close();
	}
	public static void main(String[] args) throws Exception {
		//testselect(5);
		//insert("李四",5,6,9);
		update(9,"张三");
		//delete(9);
	}
}
jdbc连接,操作
标签:exe url import 操作 connect statement int except upd