请用Java或Python语言连接自己的数据库,并对数据库中的表进行一个单表查询,在Java或Python编辑器中输出查询结果。构建一个数据库,数据库中有一个用于查询的表(包含实例),该表用自己的姓名与学号构成(如“张三610”表示6班的10号同学张三)
时间: 2023-06-16 13:04:48 浏览: 130
Python代码如下:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# 创建游标对象
mycursor = mydb.cursor()
# 执行查询语句
mycursor.execute("SELECT * FROM students")
# 获取查询结果
result = mycursor.fetchall()
# 输出查询结果
for row in result:
print(row)
```
Java代码如下:
```java
import java.sql.*;
public class DatabaseExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost/database_name", "username", "password");
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行查询语句
rs = stmt.executeQuery("SELECT * FROM students");
// 输出查询结果
while (rs.next()) {
System.out.println(rs.getString("name") + rs.getString("id"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
其中,`students` 表的结构如下:
```
+----+--------+
| id | name |
+----+--------+
| 1 | 张三610 |
| 2 | 李四611 |
| 3 | 王五612 |
+----+--------+
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)