Java操作MySQL数据库——连接数据库
1. 在数据库中建立表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 303 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
2.编写代码
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
//数据库连接
private static Connection connection;
//连接数据库的URL
private static String url = "jdbc:mysql:///blog?useSSL=false";
//连接数据库的账号
private static String username = "root";
//连接数据库的密码
private static String password = "123456";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接
connection = DriverManager.getConnection(url, username, password);
String sql = "select * from user";
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
List<User> list = new ArrayList<User>();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
String password = resultSet.getString("password");
list.add(new User(id, username, password));
}
for (User user : list) {
System.out.println(user);
}
connection.close();
}
}
class User {
private Integer id;
private String username;
private String password;
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}