我正在尝试从动态生成的textbox
gridview
数据库中插入数据。但是,我得到的例外CommandText
属性尚未初始化cmd.executeNonQuery();
private void InsertRecords(StringCollection sc)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
}
}
// conn.Open();
using (SqlConnection connn = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
{
connn.Open();
// cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connn.Close();
}
// Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
}
答案 0 :(得分:2)
您的问题是由于您在循环之后没有检查是否在StringBuilder中插入了任何内容。如果没有带逗号的字符串,那么,foreach语句中的内部条件会使stringbuilder保持为空,命令将永远不会有正确的命令文本。
解决方法应该很简单,比如添加测试以查看StringBuilder中是否有一些文本,但我更倾向于使用List<SqlParameter>
StringBuilder sb = new StringBuilder(string.Empty);
List<SqlParameter> prms = new List<SqlParameter>();
string[] splitItems = null;
// Base string for creating parameter placeholders dynamically
string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES (@p{0});";
int count = 1;
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(',');
// Parameter name created dynamically
prms.Add(new SqlParameter($"@p{count}", SqlDbType.NVarChar) {Value=splitItems[0]});
// Create the placeholder for the nth parameter
sb.AppendFormat(sqlStatement, count);
}
}
// Don't execute anything if there are no parameters (or stringbuilder empty)
if(prms.Count > 0)
{
using (SqlConnection connn = new SqlConnection(GetConnectionString()))
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
{
connn.Open();
// Add all parameters together
cmd.Parameters.AddRange(prms);
cmd.ExecuteNonQuery();
}
}
答案 1 :(得分:-1)
您没有将查询的第一部分加载到StringBuilder
。试试这个:
private void InsertRecords(StringCollection sc)
{
const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
StringBuilder sb = new StringBuilder(sqlStatement);
string[] splitItems = null;
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
}
}
// conn.Open();
using (SqlConnection connn = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
{
connn.Open();
// cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connn.Close();
}
// Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
}
编辑 - 我已经构建了一个测试数据库并调试了以下代码。它适用于我传递的测试数据。
private void InsertRecords(StringCollection sc)
{
const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
StringBuilder sb = new StringBuilder();
foreach (string item in sc)
{
if (item.Contains(","))
{
var splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
}
}
Console.WriteLine(sb.ToString());
// conn.Open();
using (SqlConnection connn = new SqlConnection(ConfigurationManager.ConnectionStrings["whatever"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
{
connn.Open();
cmd.ExecuteNonQuery();
connn.Close();
}
// Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
}
我按如下方式测试了它:
...
var collection = new StringCollection{"a,x", "b,y", "c,z"};
InsertRecords(collection);
执行数据库查询以查看数据如下:
SELECT [Ingredients1]
FROM [Ingredients_List]
结果:
Ingredients1
------------
a
b
c