java如何建立数据库_Java怎么连接数据库
时间: 2023-07-03 20:09:02 浏览: 60
Java连接数据库需要使用Java数据库连接(Java Database Connectivity,简称JDBC)API。下面是一个简单的Java连接MySQL数据库的示例:
1. 下载并安装MySQL数据库
2. 在Java项目中引入MySQL JDBC驱动,可以在官网下载或者在Maven中添加依赖。
3. 在Java代码中使用JDBC API连接数据库:
```
import java.sql.*;
public class JdbcTest {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String user = "root";
String password = "root";
conn = DriverManager.getConnection(url, user, password);
//3.创建Statement对象
stmt = conn.createStatement();
//4.执行SQL语句
String sql = "select * from user";
rs = stmt.executeQuery(sql);
//5.处理结果集
while (rs.next()) {
System.out.println(rs.getString("name") + " " + rs.getInt("age"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//6.释放资源
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
上述代码使用了MySQL数据库,通过JDBC API连接了数据库,并执行了一条查询语句。在实际开发中,还需要注意使用连接池来管理数据库连接,避免资源浪费和性能问题。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)