您的位置:首页 > 数据库 > MySQL

JDBC连接MYSQL(实现查询数据库)

2019-04-28 18:57 483 查看

一、准备工作
1、安装MySQL
2、安装Navicat Premium,因为只安装MySQL无法观看,管理具体数据库信息所以要安装Navicat Premium数据库管理工具。
3、下载下载MySQL jdbc驱动:mysql-connector-java-5.1.42-bin.jar
二、连接
1、加载数据库驱动程序
首先将上面下载的驱动程序导入项目中,之后找到Driver.class的路径,书写下述代码

Class.forName("com.mysql.jdbc.Driver");

2、连接数据库
在DriverManager.getConnection(url, user, password)中url指要连接数据库的地址,user指用户名,password指密码。

Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "");

connection对象表示一个打开的连接
3、创建sql语句对象

Statement statement = connection.createStatement();

statement对象用于传递sql语句给数据库管理系统执行。
4、书写sql语句
查询功能

String sql = "select * from use_info";//查询use_info表中所以的属性

5、执行

ResultSet resultset = = statement.executeQuery(sql);

executeQuery方法用于执行select查询语句,并返回单个结果集,保存在ResultSet对象中,下面对ResultSet对象进行的操作可以将结果打印。

while(resultset.next()) {
String id = resultset.getString("id");//记录表中id
String user_name = resultset.getString("user_name");//记录表中name
String password = resultset.getString("password");//记录表中password
System.out.println(id+","+user_name+","+password);//打印
}

其中resultset.next()一开始指向结果集中第一行元素,之后每执行一次就往后跳动一次,为空时结束循环。
6、释放资源,关闭连接
resultset.close(),statement.close(),contection.close()
注意:关闭资源时要倒序关闭。
三、具体代码及细节

public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultset = null;
String uuid = null;
String sql = null;
int affect = 0;
try {
Class.forName("com.mysql.jdbc.Driver");//加载驱动
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "");//连接数据库
statement = connection.createStatement();//创建sql对象
sql = "select * from use_info";//记录操作语句
resultset =  statement.executeQuery(sql);//返回查询结果
while(resultset.next()) {
String id = resultset.getString("id");//记录id
String user_name = resultset.getString("user_name");//记录name
String password = resultset.getString("password");//记录password
System.out.println(id+","+user_name+","+password);//打印
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (resultset!=null) {
resultset.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (statement!=null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}

执行结果:在控制台输出表中所有成员信息。

注意:此次所使用的数据库表为JDBC连接MYSQL(实现修改数据库)文章中所创建的表,且上述代码中最后的finally部分不能写成:

finally {
try {
if (resultset!=null) {
resultset.close();
}
if (statement!=null) {
statement.close();
}
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

因为若resultset.close()或者statement.close()出现异常则连接将不能断开。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: