使用C#连接sql数据库 并插入新的数据。
完整示例代码:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkDatabase2
{
internal class Program
{
static void Main(string[] args)
{
// 连接字符串,这里替换成你的数据库信息
string connectionString = "Data Source=192.168.11.11;Initial Catalog=School;User ID=sa;Password=000000";
// 创建SqlConnection对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 打开连接
connection.Open();
// SQL查询语句,这里可以替换成你自己的查询
string sql = "INSERT INTO SchoolInfo " +
"(SCID, SchoolName,SchoolAddress,SchoolTel,SchoolEmail) " +
"VALUES " +
"(2310004,'地球大学大陆学院','地月系地球大陆',231000111,'23100@gl.xy')";
// 创建SqlCommand对象
using (SqlCommand command = new SqlCommand(sql, connection))
{
// 添加参数并设置值
command.Parameters.AddWithValue("2310004", "exampleValue1");
command.Parameters.AddWithValue("地球大学大陆学院", "exampleValue2");
command.Parameters.AddWithValue("地月系地球大陆", "exampleValue3");
command.Parameters.AddWithValue("231000111", "exampleValue4");
// 执行查询,插入新数据
command.ExecuteNonQuery();
Console.WriteLine("数据插入成功!");
}
}
}
}
}
在上面的示例中,需要替换以下内容:
- serverName:SQL Server实例的名称或IP地址。
- databaseName:要连接的数据库的名称。
- username和password:连接数据库所需的用户名和密码。
- 表名和列名:要插入数据的表的名称和列的名称。
- "exampleValue1"和"exampleValue2":要插入到相应列中的值。你可以根据需要更改这些值。
本文暂时没有评论,来添加一个吧(●'◡'●)