怎么连接eclipse与数据库
时间: 2023-06-03 22:07:57 浏览: 84
你可以使用Java Database Connectivity (JDBC)技术连接Eclipse与数据库。以下是连接MySQL数据库的简单步骤:
1.下载MySQL JDBC驱动程序。
2.在Eclipse IDE中创建Java项目。
3.将驱动程序导入项目中。
4.在Java代码中编写连接数据库的代码。
示例代码:
```
import java.sql.*;
public class ConnectToDatabase {
static final String DB_URL = "jdbc:mysql://localhost/test";
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");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql = "SELECT * FROM tablename";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String age = rs.getString("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();
}
}
}
}
```
其中,DB_URL是数据库URL,USER是用户名,PASS是密码。你需要使用自己的数据库URL、用户名和密码。