string date = p_text_data.Text;
string sql = @"INSERT INTO Warehouse (title,count,price,date) ";
try
{
using (SqlConnection connection = ConnectToDataBase.GetConnection())
{
SqlCommand command = new SqlCommand(sql, connection);
for (int i = 0; i < mdc.Count; i++)
{
sql += "SELECT @title" + i + ",@count" + i + ",@price" + i + ",@date" + i + " ";
command.Parameters.AddWithValue("@title" + i, mdc[i].Title);
command.Parameters.AddWithValue("@count" + i, mdc[i].Count);
command.Parameters.AddWithValue("@price" + i, mdc[i].Price);
command.Parameters.AddWithValue("@date" + i, Conver_Data(date));
if (mdc.Count-1 != i)
sql += "UNION ALL ";
}
sql += " ;";
connection.Open();// *sql
string id_Partner = command.ExecuteScalar().ToString();
}
}
catch (SqlException se)
{
MessageBox.Show(se.Message);
}
*sql = "INSERT INTO 仓库 (标题,数量,价格,日期) SELECT @title0,@count0,@price0,@date0 UNION ALL SELECT @title1,@count1,@price1,@date1 ;"
然后他飞了一个异常(exception)
Incorrect syntax near ')'
澄清 - 计数 - 整数,价格 - double ,日期 - 日期
我做错了什么?
编辑: 表
CREATE TABLE [dbo].[Warehouse] (
[ID] int IDENTITY(1, 1) NOT NULL,
[title] char(30) COLLATE Cyrillic_General_CI_AS NULL,
[count] int NULL,
[price] float NULL,
[date] datetime NULL,
CONSTRAINT [PK__Warehous__3214EC277F60ED59] PRIMARY KEY CLUSTERED ([ID])
)
ON [PRIMARY]
GO
我使用SQL Server 2008
最佳答案
问题是您永远不会使用“)”之后的任何内容来更新 command
对象的 SQL 命令文本。仅仅因为您更新了 sql
变量并不意味着 SqlCommand
对象会看到该更新。
(您将遇到的另一个问题是您不会从此查询返回任何内容,因此您将无法使用 ExecuteScalar()
。)
试试这个:
string date = p_text_data.Text;
string sql = @"INSERT INTO Warehouse (title,count,price,date) ";
try
{
using (SqlConnection connection = ConnectToDataBase.GetConnection())
{
SqlCommand command = new SqlCommand(sql, connection);
for (int i = 0; i < mdc.Count; i++)
{
sql += "SELECT @title" + i + ",@count" + i + ",@price" + i + ",@date" + i + " ";
command.Parameters.AddWithValue("@title" + i, mdc[i].Title);
command.Parameters.AddWithValue("@count" + i, mdc[i].Count);
command.Parameters.AddWithValue("@price" + i, mdc[i].Price);
command.Parameters.AddWithValue("@date" + i, Conver_Data(date));
if (mdc.Count-1 != i)
sql += "UNION ALL ";
}
sql += " ;";
command.CommandText = sql; // Set your SQL Command to the whole statement.
connection.Open();// *sql
command.ExecuteNonQuery(); // Execute a query with no return value.
}
}
catch (SqlException se)
{
MessageBox.Show(se.Message);
}
关于c# - 如何在表中添加多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3831129/