java连接MySQL数据库操作步骤

时间:2021-07-25 13:05:31
package com.swift;
//这里导入的包是java.sql.Connection而不是com.mysql.jdbc.Connection
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class TestJDBC {

public static void main(String[] args) {
Connection conn
=null;
Statement st
=null;
ResultSet rs
=null;
try {
//1、装载驱动
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
//2、链接数据库,使用com.mysql.jdbc.Connection包会出错
List<User> list=new ArrayList<User>();
conn
=DriverManager.getConnection("jdbc:mysql://localhost:3306/sw_database?user=root&password=root");
//3、创建连接语句
st=conn.createStatement();
//4、执行SQL语句获得结果集
rs=st.executeQuery("select * from sw_user");
//5、循环获得数据库字段生成对象
while(rs.next()) {
int id=rs.getInt("id");
String username
=rs.getString("username");
String password
=rs.getString("password");
User user
=new User(id,username,password);
list.add(user);
}
//6、遍历对象列表
for(User user:list) {
System.out.println(user.toString());
}

}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
//7、关闭结果集
try {
if(rs!=null) {
rs.close();
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//7、关闭连接语句
try {
if(st!=null) {
st.close();
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//7、关闭数据库连接
try {
if(conn!=null) {
conn.close();
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}