使用Myelipse软件(Java语言)或Visual Studio(C#语言)软件或PyCharm软件(Python语言)创建控制台应用程序,使用实验一创建的用户名sa与密码连接数据库study2,并在控制台中显示单位表中的数据
时间: 2024-09-26 17:13:11 浏览: 66
在创建控制台应用程序并连接到数据库的过程中,首先需要安装相应的开发环境。这里以Java的MyEclipse为例:
1. **Java (MyEclipse):**
- 打开MyEclipse,选择"File" -> "New" -> "Other" -> "Java Project",然后填写项目名称和路径。
- 配置JDBC驱动:右键点击项目 -> "Properties" -> "Java Build Path" -> "Libraries", 点击"Add External JARs",找到并添加MySQL的JDBC驱动jar文件(mysql-connector-java.jar)。
- 在src目录下新建一个Java类,例如`DatabaseConnection.java`,编写如下代码,用于连接数据库:
```java
import java.sql.*;
public class DatabaseConnection {
private static final String URL = "jdbc:mysql://localhost/study2";
private static final String USER = "sa";
private static final String PASS = "password"; // 请注意替换为实际密码
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection(URL, USER, PASS);
System.out.println("Connected to the database!");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM units");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// ...其他字段处理
System.out.printf("ID: %d, Name: %s%n", id, name);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
2. **C# (Visual Studio):**
- 新建一个控制台应用项目,在App.config里配置数据库连接字符串(注意替换真实的username和password):
```xml
<connectionStrings>
<add name="Study2ConnectionString" connectionString="Data Source=(local);Initial Catalog=study2;User ID=sa;Password=password;" providerName="System.Data.SqlClient"/>
</connectionStrings>
```
在代码中使用ADO.NET操作数据库,示例如下:
```csharp
using System;
using System.Data.SqlClient;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection(Configuration.GetConnectionString("Study2ConnectionString")))
{
connection.Open();
string query = "SELECT * FROM units";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
// ...其他字段处理
Console.WriteLine($"ID: {id}, Name: {name}");
}
}
}
}
}
```
3. **Python (PyCharm):**
- 使用Python的sqlite3库连接SQLite(如果study2是SQLite数据库),或者pymysql或pyodbc连接MySQL,代码类似:
```python
import pymysql
def connect_database():
conn = pymysql.connect(host='localhost', user='sa', password='password', db='study2')
return conn
def fetch_units(conn):
with conn.cursor() as cursor:
cursor.execute("SELECT * FROM units")
rows = cursor.fetchall()
for row in rows:
id, name = row
print(f"ID: {id}, Name: {name}")
if __name__ == "__main__":
conn = connect_database()
fetch_units(conn)
conn.close()
```
阅读全文