java实现应用程序链接数据库
时间: 2023-05-29 08:05:36 浏览: 114
Java可以使用JDBC(Java Database Connectivity)来连接数据库。以下是一个简单的Java程序,演示如何连接MySQL数据库并执行一些基本操作:
1. 首先需要下载并安装MySQL JDBC驱动程序。可以从MySQL官网下载,或者使用Maven等构建工具来管理依赖。
2. 导入所需的Java类:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
```
3. 建立数据库连接:
```java
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
```
其中,url是数据库连接的URL,user和password是登录数据库的用户名和密码。
4. 执行SQL语句:
```java
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
```
此代码将从名为“students”的表中检索所有行,并将它们打印到控制台。
5. 关闭连接:
```java
rs.close();
stmt.close();
conn.close();
```
完整的示例程序如下所示:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseDemo {
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
rs.close();
stmt.close();
conn.close();
}
}
```
阅读全文