我已经创建了一个方法并在保存按钮上调用它。我想将富文本框的所有行分别保存在SQL数据库中的不同行中。即时帮助将不胜感激。
private void SaveData()
{
xConn.Open();
new SqlCommand("insert into tbldata values('"+DateTime.Now.ToString()+"','"+richTextBox1.Text+"')", xConn).ExecuteNonQuery();
xConn.Close();
}
你不会连迭代在RichTextBox中的每一行。您只需插入当前文本即可。您可以使用它的Lines
属性,该属性以字符串数组形式返回文本行。
另外,请勿在您的DateTime
值中插入字符串的“ representaiton”。将其值直接插入到参数化查询中。顺便说一句,这种字符串连接方式可用于SQL注入攻击。
您应该始终为列类型考虑正确的数据类型。阅读:不良习惯:选择错误的数据类型
private void SaveData()
{
using(var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "insert into tbldata values(@date, @text)";
string[] lines = richTextBox1.Lines;
foreach(var line in lines)
{
cmd.Parameters.Clear();
cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Now;
// Change your first column type to datetime or datetime2
cmd.Parameters.Add("@text", SqlDbType.NVarChar).Value = line;
// I assume your second column is nvarchar
if(con.State != ConnectionState.Open)
con.Open();
cmd.ExecuteNonQuery();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句