给我一个jdbc连接代码
时间: 2024-05-02 09:20:57 浏览: 6
这是一个简单的JDBC连接代码,可以连接到MySQL数据库:
```java
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
// Database credentials
String USER = "root";
String PASS = "password";
Connection conn = null;
Statement stmt = null;
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, name, age FROM users";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try
System.out.println("Goodbye!");
}
}
```
请注意,您需要将“mydatabase”更改为您实际的数据库名称,并将“root”和“password”更改为您的MySQL用户名和密码。