JDBC练习一

JDBC练习一

import java.sql.*;

public class JDBCTest01 {
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		try{
			// 1、注册驱动
			Driver driver = new com.mysql.jdbc.Driver();	//多态,父类型引用指向子类型对象
			DriverManager.registerDriver(driver);
			
			// 2、获取连接
			/*
				url包括哪几部分:
					协议
					IP
					Port
					资源名
				
				eg:http://180.101.49.11:80/index.html
					http:// 通信协议
					180.101.49.11 IP地址
					80 端口号
					index.html 资源名
			*/
			// static Connection getConnection(String url, String user, String password)
			String url = "jdbc:mysql://127.0.0.1:3306/mydb";
			String user = "root";
			String password = "123456";
			conn = DriverManager.getConnection(url,user,password);
			System.out.println("数据库连接对象" + conn);	//数据库连接对象com.mysql.jdbc.JDBC4Connection@1ae369b7

			// 3、获取数据库操作对象
			// Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库。
            stmt = conn.createStatement();

			// 4、执行sql语句
			// int executeUpdate(String sql) 
            // 专门执行DML语句
			// 返回值是“影响数据库中的记录条数”
			int count = stmt.executeUpdate("insert into student values(5,'田七')");
			System.out.println(count == 1 ? "保存成功":"保存失败");
            
			// 5、处理查询结果集

		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			// 6、释放资源
			// 从小到大依次关闭(后进先出)
			if(stmt != null) {
				try	{
					stmt.close();	
				}
				catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try	{
					conn.close();	
				}
				catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
运行结果:

image-20210920190157499

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值