主要就是把using的写法改变了
using System.Data.SqlClient;string conStr = "Data Source = WINGEL; Initial Catalog = People; Trusted_Connection = SSPI";using SqlConnection conn = new SqlConnection(conStr);
string sql = "insert into dbo.Student values(1,'WinGel')";using SqlCommand cmd = new SqlCommand(sql,conn);conn.Open();// r 为受影响的行数
int r = cmd.ExecuteNonQuery(); // insert updata delete
if (r > 0)
{Console.WriteLine("执行成功");
}
else
{Console.WriteLine("执行失败");
}
其他不常用的写法:
第一种:
using System.Data.SqlClient;string conStr = "Data Source = WINGEL; Initial Catalog = People; Trusted_Connection = SSPI";using SqlConnection conn = new SqlConnection(conStr);
string sql = "insert into dbo.Student values(1,'WinGel')";using SqlCommand cmd = new();
cmd.CommandText = sql; // 指定执行的sql语句
cmd.Connection = conn; // 指定连接的数据库conn.Open();// r 为受影响的行数
int r = cmd.ExecuteNonQuery(); // insert updata delete
if (r > 0)
{Console.WriteLine("执行成功");
}
else
{Console.WriteLine("执行失败");
}
第二种:
using System.Data.SqlClient;string conStr = "Data Source = WINGEL; Initial Catalog = People; Trusted_Connection = SSPI";using SqlConnection conn = new SqlConnection(conStr);
string sql = "insert into dbo.Student values(1,'WinGel')";using SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql; 指定执行的SQL语句conn.Open();// r 为受影响的行数
int r = cmd.ExecuteNonQuery(); // insert updata delete
if (r > 0)
{Console.WriteLine("执行成功");
}
else
{Console.WriteLine("执行失败");
}