JDBC连接总结(模板、八股文)

a、导入驱动包,加载具体驱动类Class.forName(“具体驱动类”)

b、与数据库建立连接:connection = DriverManage.getConnection(URL,UNAME,UPWD)

C、通过connection,获取到操作数据库的对象。例如:prstmt = conn.prepareStatement(sql);

(查询)处理结果集rs=pstmt.executeQuary();

完整步骤:`public static final String DBDRIVER = “com.mysql.cj.jdbc.Driver”;

public static final String DBURl = "jdbc:mysql://localhost:3306/Student?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"; 
public static final String DBUSER = "root"; 
public static final String DBPASS = "qwert123";

public static void main(String[] args) {
	Connection conn = null;
	PreparedStatement prstmt = null;
	ResultSet rs = null;
	try {
		//导入驱动程序
		Class.forName(DBDRIVER);
		//与数据库建立连接
		conn=DriverManager.getConnection(DBURl,DBUSER,DBPASS);
		//编写sql语句(增删改查)
		//增
		String sql  = "insert into student values(1020,'zhangsan','women','class8',95,null)";
		//删
		String delsql="delete from student where id =1021";
		//改
		String updsql="update student set name='wangqi' where id =1009 ";
		//查
		String selsql="SELECT * FROM student WHERE name like ?";
		//执行sql
		prstmt = conn.prepareStatement(selsql);//预编译
		prstmt.setString(1, "%ang%");
		rs = prstmt.executeQuery();  //这边括号中可不写sql

最后关闭的流程:

	
		
		try {
			if(rs!=null)
				rs.close();
			if(prstmt!=null)
				prstmt.close();
			if (conn!=null) 
				conn.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值