请写一个用java连接数据库的程序
时间: 2023-04-02 21:04:13 浏览: 96
Java SE程序 连接数据库的分页
可以的,以下是一个用 Java 连接数据库的程序示例:
import java.sql.*;
public class ConnectDatabase {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/DBNAME";
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("com.mysql.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!");
}
}
请注意,这只是一个示例程序,实际上,您需要根据您的数据库类型和配置更改连接字符串、用户名和密码。
阅读全文