问题描述
我正在尝试将列表视图中的数据发送到数据库中.我的列表视图有5列,我的数据库有5个字段.以我编写插入内容的方式-将包含所有五列信息的整行插入数据库的一个字段中.我可以解析该字符串以正确插入其字段的每一列.这是我的代码:
I am trying to send data that i have in the list view into my database. my list view has 5 columns and my database has 5 fields. the way i wrote the insert - it inserts an entire row with all five column information into one field in the database. I could i parse through the string to properly insert every column with its field. here is my Code:
private void btnSave_Click(object sender, EventArgs e)
{
//save listview to database
conn.Open();
for (int cnt = 0; cnt <= listView1.Items.Count; cnt++)
{
string query = "insert into Log values(''" + listView1.Items[cnt].Text +"'')";
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
}
conn.Close();
推荐答案
字符串查询=插入日志values(''"+ listView1.Items [cnt] .Text +"'');
string query = "insert into Log values(''" + listView1.Items[cnt].Text +"'')";
这完全符合您的要求.如果用户能够输入文本,那么他们也可以擦除您的数据库,因为这写得不好.您应该使用参数化查询并使其生效,以使它提取出所需的值,而不是将它们全部作为一个值传递.
它被称为listview1的事实使我认为您只是在编写代码而已,很有趣.如果您想编写生产质量代码,请阅读SQL注入.
另一件事是,查看生成的SQL,然后考虑它的功能以及需要如何更改以执行所需的操作.指定要插入的列是使此操作崩溃或执行所需操作的一种方法(而不是工作"但未执行您希望的操作)
This does exactly what you asked. IF the user was able to enter the text, then they can also erase your DB because this is badly written. You should use parameterised queries and make it so that it pulls out the values you need, instead of passing them all as one value.
The fact that it''s called listview1 makes me think you''re just writing code for fun, and that''s cool. read up on SQL injection, if you ever want to write production quality code.
The other thing is, look at the SQL you generate, then think about what it does, and how it needs to change to do what you want. Specifying the columns you want to insert into is one way to make this either crash or do what you want ( instead of ''working'' but not doing what you hoped it would )
这篇关于Listview数据到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!