eclipse连接数据库的代码
时间: 2023-09-05 14:10:07 浏览: 44
可以使用以下代码来连接数据库:
```
import java.sql.*;
public class DBConnector {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/yourDBname";
static final String USER = "yourDBusername";
static final String PASS = "yourDBpassword";
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("Connected to database successfully...");
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
```
请注意,这段代码仅适用于MySQL数据库,并且您需要将“yourDBname”、“yourDBusername”和“yourDBpassword”替换为您自己的数据库名称、用户名和密码。