【问题标题】:unrecognized token: "4eL2" c# SQLITE无法识别的令牌:“4eL2”c#SQLITE
【发布时间】:2014-08-08 13:39:47
【问题描述】:

我的问题是我正在尝试将图像 .tif 存储在 sqlite 数据库中,我将图像转换为 base64String,但在执行查询时会出现异常

"SQL 逻辑错误或缺少数据库 无法识别的令牌:“4eL2””

这是我的代码:

Bitmap bitmap =(Bitmap)System.Drawing.Image.FromFile(@"C:\Users\myuser\Desktop\Images\myimage.TIF");
ImageConverter converter = new ImageConverter();
byte [] b =  (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
string base64String = Convert.ToBase64String(b);
SaveImage(base64String);

void SaveImage(string pic)
        {
            string query = "insert into mytable (date, imagen) values (2014, "+pic+");";
            string conString = @" Data Source = C:\Users\myuser\Documents\Visual Studio 2012\Projects\images.sqlite3";
            SQLiteConnection con = new SQLiteConnection(conString);
            SQLiteCommand cmd = new SQLiteCommand(query, con);

            con.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (SQLiteException exc1)
            {
                MessageBox.Show(exc1.Message);
            }
            con.Close();
        }

【问题讨论】:

    标签: sql sqlite c#-4.0 exception


    【解决方案1】:

    由于pic 是字符串数据,因此您需要将其用引号括起来以进行查询:

    string query = "insert into mytable (date, imagen) values (2014, '"+pic+"');";
    

    【讨论】:

    • 请使用参数化查询!这很容易受到 SQL 注入的攻击。
    【解决方案2】:

    我是这样用的:

    void SaveImage(byte[] imagen)
            {
                string conStringDatosUsuarios = @" Data Source = C:\Users\myuser\Documents\Visual Studio 2012\Projects\images.sqlite3";
                SQLiteConnection con = new SQLiteConnection(conStringDatosUsuarios);
                SQLiteCommand cmd = con.CreateCommand();
                cmd.CommandText = String.Format("INSERT INTO imagenes (date, imagen) VALUES ('01/01/2014', 'DIRIGIDO A QUIEN LE INTERESE', '2014', @0);");
                SQLiteParameter param = new SQLiteParameter("@0", System.Data.DbType.Binary);
                param.Value = imagen;
                cmd.Parameters.Add(param);
                con.Open();
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception exc1)
                {
                    MessageBox.Show(exc1.Message);
                }
                con.Close();
            }
    

    在 .sqlite3 中,我将列 imagen 放入 blob 数据类型

    【讨论】:

      【解决方案3】:
      sqlite_cmd.CommandText = String.Format("insert into mytable (date, imagen) values ({0}, '{1}');", 2014, pic);
      

      pic 是一个字符串,所以应该用单引号(')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 1970-01-01
        • 1970-01-01
        • 2018-10-29
        相关资源
        最近更新 更多