我有这个程序正在为我提供数据。我获取此数据(字符串)并解析它,以便不同的字段可以进入相应的数据库表列。我可以解析字符串,但我找不到正确的函数或方式将它们发送到数据库。这是我第二次使用sql server或数据库。我这样做了插入
MyCommand.CommandType = System.Data.CommandType.Text;
MyCommand.CommandText = "INSERT INTO TimeStampTable(ID, TimeStamp) VALUES ('24', 'sep 13, 2009')";
据我所知,CommandType只允许文本或存储过程。在这种情况下,我想插入正在解析的字符串。
string teststring = dtString;
string[] result = teststring.Split(',', ' ', ':', '=');
Console.WriteLine("The parsed string looks like this:");
foreach (string word in result)
{
Console.WriteLine(word);
}
这是我解析传入字符串的代码。所以我收到名称地址zip状态等等。我想要名字去col1,地址去col2等等。我认为这样做的理想方法是将我的循环转换成这样的东西
foreach (string word in result)
{
SqlDatasource.InsertCommand=Insert into Tablename col1 col2 col3(word);
}
有人有任何建议吗?
答案 0 :(得分:1)
我会直接回答你的问题,但你可以采取多种不同的方式来执行同样的事情(我会在最后列出一些)
String insertQuery = "INSERT INTO TABLENAME (Col1, Col2, Col3...) VALUES (";
//This is also assuming that your data is in the same order as the columns
int isFirstLoop = true
foreach(string word in result)
{
if(!isFirstLoop)
insertQuery += ","
insertQuery += word;
isFirstLoop = false;
}
insertQuery += ")";
SqlDataSource.InsertCommand = insertQuery;
注意:这对SQL Injection非常开放,所以请记住(你相信你的来源)吗?有方法可以清理数据,但最终,我建议使用下面列出的一些方法
备选方案: