用Java语言创建MySQL数据库JDBC,数据表users,字段有:Id(自动递增)、name(40)、password(40)、emai(60)、birthday,通过JDBC的常用API连接Mysql 数据库,输出数据表users中的所有记录。
时间: 2024-12-28 17:36:16 浏览: 6
在Java中,我们可以使用JDBC(Java Database Connectivity)来连接MySQL数据库并操作数据。首先,需要添加MySQL JDBC驱动到项目中。下面是一个简单的步骤说明如何创建数据库、数据表以及查询数据:
1. **添加JDBC驱动**:
将`mysql-connector-java.jar`库添加到项目的类路径中,或者在Maven或Gradle构建文件中添加依赖。
2. **配置数据库连接**:
使用JDBC URL(如jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC`),用户名和密码建立Connection对象。
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCDemo {
private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USER = "your_username";
private static final String PASS = "your_password";
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
// 添加创建用户表的方法
public static void createUserTable() {
String createTableQuery =
"CREATE TABLE IF NOT EXISTS users (" +
"id INT AUTO_INCREMENT PRIMARY KEY," +
"name VARCHAR(40)," +
"password VARCHAR(40)," +
"email VARCHAR(60)," +
"birthday DATE)";
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate(createTableQuery);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 查询所有用户记录的方法
public static void getAllUsers() {
String selectAllQuery = "SELECT * FROM users";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(selectAllQuery)) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String password = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println("ID: " + id + ", Name: " + name + ", Password: " + "[hidden for security] " + ", Email: " + email + ", Birthday: " + birthday);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们首先加载MySQL驱动,然后获取连接。接着创建数据表`users`,最后编写查询语句获取并打印出所有用户记录。注意,为了安全,实际应用中不应将密码硬编码并在控制台上显示。
阅读全文