使用c#应用程序错误将数据集导出到sqlite3数据库sqlexception unhandled

时间:2014-01-30 16:24:42

标签: c# sqlite

我是sqlite和c#的新手,并尝试使用数据集将csv文件导出到sqlite数据库。  但是我得到了这个错误。

SQL logic error or missing database
    no such column: P17JAW  

代码:

 string strFileName = "I:/exploretest.csv";
            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
            conn.Open();
            OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
            DataSet ds = new DataSet("Temp");
            adapter.Fill(ds);

            DataTable tb = ds.Tables[0];
            SQLiteConnection m_dbConnection;
            m_dbConnection = new SQLiteConnection("Data Source= C:/Users/WebMobility.db; Version=3;");

         m_dbConnection.Open();
        var dt = ds.Tables[0];

        foreach (DataRow dr in dt.Rows)
        {
            var Id = dr["Id"].ToString();
            var VRM = dr["VehicleRegistration"].ToString();
            var Points = Convert.ToInt32(dr["TicketScore"].ToString());
            string sql = "insert into NaughtyList (Id,VRM,Points) values ( '" + Id + "'," + VRM + "," + Points + ")";
            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
            command.ExecuteNonQuery();
        }
        m_dbConnection.Close();
    }

CSV文件包含

Id,VehicleRegistration,TicketScore
21,P17JAW,1
22,K1WOM,1
23,m4npr,4
25,G7EPS,4

1 个答案:

答案 0 :(得分:0)

您的问题是VRM缺少单引号,您的查询应该是:

string sql = @"insert into NaughtyList (Id,VRM,Points) values 
                       ( '" + Id + "','" + VRM + "'," + Points + ")";
                                    //^^          ^^

ID为整数类型的值显示,您可以删除ID周围的单引号。

您应该参数化您的查询,以避免这些错误。我不确定SQLiteCommand是否支持参数,如果它们可以执行以下操作:

string sql = @"insert into NaughtyList (Id,VRM,Points) values 
                                       (@Id,@VRM,@Points)";

然后

command.Parameters.AddWithValue("@id", Id);
command.Parameters.AddWithValue("@VRM", VRM);
command.Parameters.AddWithValue("@Points", Points);