用C#连接数据库创建疫苗表(编号、名称、注射量、保质期、价格); 添加5条测试数据 实现增删改查
时间: 2024-01-31 16:04:53 浏览: 107
首先,需要安装并引用相应的数据库驱动程序,比如MySQL的Connector/NET或者Microsoft SQL Server的System.Data.SqlClient。
接下来,可以使用以下代码创建一个名为“vaccine”的表,包括编号、名称、注射量、保质期和价格五个列:
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
class Program {
static void Main(string[] args) {
string connectionString = "data source=YourServerName;initial catalog=YourDatabaseName;user id=YourUserName;password=YourPassword;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = connection;
command.CommandText = "CREATE TABLE vaccine (id int PRIMARY KEY, name varchar(50), dosage decimal(5,2), shelf_life int, price decimal(8,2))";
command.ExecuteNonQuery();
}
connection.Close();
}
}
}
```
其中,connectionString字符串需要替换成实际的连接字符串,YourServerName、YourDatabaseName、YourUserName和YourPassword分别表示数据库服务器名称、数据库名称、用户名和密码。
接下来,可以使用以下代码向表中添加5条测试数据:
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
class Program {
static void Main(string[] args) {
string connectionString = "data source=YourServerName;initial catalog=YourDatabaseName;user id=YourUserName;password=YourPassword;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = connection;
command.CommandText = "INSERT INTO vaccine (id, name, dosage, shelf_life, price) VALUES (1, '疫苗1', 0.5, 365, 100.00), (2, '疫苗2', 0.3, 180, 50.00), (3, '疫苗3', 0.2, 90, 30.00), (4, '疫苗4', 0.1, 60, 20.00), (5, '疫苗5', 0.4, 270, 80.00)";
command.ExecuteNonQuery();
}
connection.Close();
}
}
}
```
类似地,可以使用以下代码实现对疫苗表的增删改查操作:
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
class Program {
static void Main(string[] args) {
string connectionString = "data source=YourServerName;initial catalog=YourDatabaseName;user id=YourUserName;password=YourPassword;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = connection;
// 插入一条新记录
command.CommandText = "INSERT INTO vaccine (id, name, dosage, shelf_life, price) VALUES (6, '疫苗6', 0.6, 180, 120.00)";
command.ExecuteNonQuery();
// 修改一条记录
command.CommandText = "UPDATE vaccine SET price=150.00 WHERE id=1";
command.ExecuteNonQuery();
// 删除一条记录
command.CommandText = "DELETE FROM vaccine WHERE id=2";
command.ExecuteNonQuery();
// 查询所有记录
command.CommandText = "SELECT * FROM vaccine";
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
Console.WriteLine("编号: {0}, 名称: {1}, 注射量: {2}, 保质期: {3}, 价格: {4}", reader.GetInt32(0), reader.GetString(1), reader.GetDecimal(2), reader.GetInt32(3), reader.GetDecimal(4));
}
reader.Close();
}
connection.Close();
}
}
}
```
需要注意的是,以上代码只是示例,实际开发中需要根据具体情况进行修改和完善。
阅读全文