当前位置:网站首页>JDBC连接数据库
JDBC连接数据库
2022-04-23 05:42:00 【hanyc..】
主要步骤:
1、加载数据库驱动
2、获取数据库连接(包含了获取用户信息、url)
3、创建执行sql的对象
4、执行sql语句
5、返回执行的结果集
6、释放连接
package com.hyc.study01;
import java.sql.*;
public class JdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1、加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取用户信息、url
//jdbcstudy是要连接的数据库的名称
//useUnicode=true&characterEncoding=utf8&useSSL=true 支持中文编码&设定中文字符集为utf8&使用安全的连接
String url =
"jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String psw = "123456";
//3、获取数据库连接
//这里的Connection就代表了数据库,如果返回的对象不为空,代表数据库就拿到了
Connection connection = DriverManager.getConnection(url, username, psw);
//4、创建用来执行sql的对象
Statement statement = connection.createStatement();
//5、执行sql语句
//6、返回执行结果集
String sql = "SELECT * FROM users";
//执行查询sql语句,得到返回的结果集
ResultSet resultSet = statement.executeQuery(sql);//返回的结果集是一个链表的形式
while (resultSet.next()) {
System.out.println("id=" + resultSet.getInt("id"));
System.out.println("name=" + resultSet.getString("NAME"));
System.out.println("psw=" + resultSet.getString("PASSWORD"));
System.out.println("email=" + resultSet.getString("email"));
System.out.println("birth=" + resultSet.getDate("birthday"));
System.out.println("=====================================================");
}
//int num = statement.executeUpdate("add delete update sql");
//增删改都用statement.executeUpdate(),该方法返回执行sql语句受影响的行数
//7、释放连接
resultSet.close();
statement.close();
connection.close();
}
}
数据库以及数据库表:
版权声明
本文为[hanyc..]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42732184/article/details/124215610
边栏推荐
猜你喜欢
jdbc入门\获取数据库连接\使用PreparedStatement
Some pits used by uni
Flutter nouvelle génération de rendu graphique Impeller
Sea Level Anomaly 和 Sea Surface Height Anomaly 的区别
Flutter 新一代图形渲染器 Impeller
2 - principes de conception de logiciels
deep learning object detection
Flutter 新一代圖形渲染器 Impeller
Pol / select / EPO
引航成长·匠心赋能——YonMaster开发者培训领航计划全面开启
随机推荐
ES6之解构函数
热键,界面可视化配置(界面交互)
The 8th Blue Bridge Cup 2017 - frog jumping cup
mysql sql优化之Explain
What is JSON? First acquaintance with JSON
2.devops-sonar安装
io. lettuce. core. RedisCommandExecutionException: ERR wrong number of arguments for ‘auth‘ command
windows连接mysql出现ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost‘ (10061)
POI exports to excel, and the same row of data is automatically merged into cells
Common interview questions - 4 (MySQL)
Xiuxian real world and game world
Usage and difference of shellexecute, shellexecuteex and winexec in QT
Interview Basics
Frequently asked interview questions - 2 (computer network)
Differences between sea level anatomy and sea surface height anatomy
Redis经典面试题总结2022
Frequently asked interview questions - 3 (operating system)
[machine learning] scikit learn introduction
踩坑:nacos利用startup.cmd -m standalone启动错误
2-软件设计原则