gpt4 book ai didi

c# - 如何在表格中添加多行?

转载 作者:行者123 更新时间:2023-11-30 22:43:42 24 4
gpt4 key购买 nike

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 Warehouse (title,count,price,date) SELECT @title0,@count0,@price0,@date0 UNION ALL SELECT @title1,@count1,@price1,@date1 ;"

然后他飞了个异常(exception)

Incorrect syntax near ')'

clarify - count - int, price - double, date - 日期

我做错了什么?

编辑:表格

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com