r.v*_*esh 0 c# database-connection console-application
我是控制台应用程序的新手.现在我为数据库中的插入值编写了一个示例函数.我的数据库连接没有问题.但我的valuse没有插入表中.请找到问题并告诉我.
这是我的代码
static void Main(string[] args)
{
try
{
string sConnectionString = "Data Source=my ipaddress;Network Library=DBMSSOCN;Initial Catalog=db;user id=user;Password=password";
string sSQL = "";
using (var connection = new SqlConnection(sConnectionString))
{
connection.Open();
Console.WriteLine("OK");
for (int i = 1; i <= 5; i++)
{
sSQL = "INSERT INTO test " +
"(id) " +
"VALUES (" + i + ")";
Console.WriteLine(i + " inserted successfully");
}
SqlCommand objCmd = new SqlCommand(sSQL, connection);
}
}
catch (DbException)
{
Console.WriteLine("NOT OK");
}
}
Run Code Online (Sandbox Code Playgroud)
你根本没有执行命令 - 你正在创建一个SqlCommand,然后对它做任何事情.你需要打电话ExecuteNonQuery().
但是,您也应该停止构建这样的SQL.你应该开始使用参数化的SQL 现在.像这样的东西:
using (var connection = new SqlConnection(sConnectionString))
{
connection.Open();
var sql = "INSERT INTO test (id) VALUES (@id)";
using (var command = new SqlCommand(sql, connection))
{
// Adjust this to match the type of the id field
var parameter = command.Parameters.Add("@id", SqlDbType.Int);
for (int i = 1; i <= 5; i++)
{
parameter.Value = i;
command.ExecuteNonQuery();
}
}
}
Run Code Online (Sandbox Code Playgroud)