c#往sqlserver中Adv数据库中的PointTab表写入数据并输出到控制台
时间: 2024-02-17 16:05:08 浏览: 68
可以使用C#的ADO.NET技术与SQL Server进行交互,具体的步骤如下:
1. 引入命名空间
```csharp
using System.Data.SqlClient;
```
2. 建立数据库连接
```csharp
string connectionString = "Data Source=<server_name>;Initial Catalog=<database_name>;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
```
其中,`<server_name>`为SQL Server的名称,`<database_name>`为要连接的数据库名称。
3. 打开数据库连接
```csharp
connection.Open();
```
4. 创建SQL语句并执行
```csharp
string sql = "INSERT INTO PointTab (x, y, z) VALUES (1.0, 2.0, 3.0);";
SqlCommand command = new SqlCommand(sql, connection);
int rowsAffected = command.ExecuteNonQuery();
```
其中,`PointTab`为要插入数据的表名,`(x, y, z)`为表中的列名,`VALUES (1.0, 2.0, 3.0)`为要插入的数据。`ExecuteNonQuery`方法返回受影响的行数,可以用来判断插入是否成功。
5. 查询插入的数据并输出到控制台
```csharp
string selectSql = "SELECT * FROM PointTab;";
SqlCommand selectCommand = new SqlCommand(selectSql, connection);
SqlDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
double x = reader.GetDouble(0);
double y = reader.GetDouble(1);
double z = reader.GetDouble(2);
Console.WriteLine($"x={x}, y={y}, z={z}");
}
```
其中,`SELECT * FROM PointTab`为要查询的SQL语句,`SqlDataReader`对象用于读取查询结果,`GetDouble`方法用于获取列的值。
6. 关闭数据库连接
```csharp
connection.Close();
```
完整的代码如下:
```csharp
using System;
using System.Data.SqlClient;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=<server_name>;Initial Catalog=<database_name>;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string sql = "INSERT INTO PointTab (x, y, z) VALUES (1.0, 2.0, 3.0);";
SqlCommand command = new SqlCommand(sql, connection);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"Rows affected: {rowsAffected}");
string selectSql = "SELECT * FROM PointTab;";
SqlCommand selectCommand = new SqlCommand(selectSql, connection);
SqlDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
double x = reader.GetDouble(0);
double y = reader.GetDouble(1);
double z = reader.GetDouble(2);
Console.WriteLine($"x={x}, y={y}, z={z}");
}
connection.Close();
}
}
}
```
需要将`<server_name>`和`<database_name>`替换为实际的值。
阅读全文