java如何连接数据库
时间: 2023-10-18 16:05:27 浏览: 89
Java可以使用JDBC(Java Database Connectivity) API连接数据库。开发者需要使用JDBC驱动程序来连接不同的数据库,例如MySQL、Oracle、SQL Server等等。下面是一个连接MySQL数据库的示例代码:
```java
import java.sql.*;
public class JDBCDemo {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test";
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM student";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.print("ID: " + id);
System.out.print(", 姓名: " + name);
System.out.println(", 年龄: " + age);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
阅读全文