java实现数据库管理
时间: 2023-07-30 10:10:47 浏览: 169
Java可以通过JDBC(Java Database Connectivity)技术来实现数据库管理,JDBC是一种Java API,可用于连接各种类型的关系型数据库。下面是一个简单的Java程序示例,用于连接数据库并执行SQL查询:
```
import java.sql.*;
public class DatabaseManager {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/employee";
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);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
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.println(", Age: " + 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!");
}
}
```
此程序将连接到名为“employee”的MySQL数据库,并从“employees”表中检索数据。请注意,您必须替换USER和PASS变量中的值以匹配您的MySQL用户名和密码。
阅读全文