mysql java基础
时间: 2023-10-12 17:20:32 浏览: 60
MySQL是一种关系型数据库管理系统,它使用SQL语言来查询和操作数据。Java作为一种高级编程语言,可以与MySQL数据库进行交互,实现数据的存储、查询和更新等操作。
在Java中,我们可以使用JDBC(Java Database Connectivity)来连接数据库。JDBC是Java提供的一套标准API,用于与各种关系型数据库进行交互。我们可以通过JDBC驱动程序连接到MySQL数据库,并使用SQL语句进行数据的操作。
以下是一个简单的Java程序,演示如何连接MySQL数据库并执行查询操作:
```java
import java.sql.*;
public class MySQLDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
conn = DriverManager.getConnection(url, user, password);
// 创建Statement对象
stmt = conn.createStatement();
// 执行查询操作
String sql = "SELECT * FROM student";
rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
在这个程序中,我们首先加载MySQL的JDBC驱动程序(com.mysql.jdbc.Driver),然后建立连接,创建Statement对象,执行查询操作,并处理查询结果。最后释放资源。
当然,这只是一个简单的示例,实际上我们在Java中可以使用JDBC来完成各种数据操作,如插入、更新、删除等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)