java如何连接数据库
时间: 2023-07-03 13:07:56 浏览: 88
连接数据库需要用到Java中的JDBC(Java Database Connectivity)技术。下面是一个简单的连接MySQL数据库的示例代码:
```java
import java.sql.*;
public class ConnectMySQL {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/TESTDB";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM Employees";
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: " + name);
System.out.print(", Age: " + age);
System.out.println();
}
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!");
}
}
```
其中,JDBC驱动程序需要先加载,然后创建一个连接对象(Connection),利用连接对象创建一个Statement对象,执行SQL语句并返回结果集(ResultSet),最后关闭连接、语句和结果集对象。这里的例子是查询Employees表中的id、name和age字段。
阅读全文