我想在Visual Studio C#代码中提供一些帮助,将unicode字符串插入到SQLite数据库中。
下面是我将测试字符串写入数据库的测试代码:
string testStr = "á Á ñ ç é á";
SQLiteConnection mydataConnection = new SQLiteConnection(); // setup new sql connection obj
try
{
//// SQLite DB
mydataConnection.ConnectionString =
"Data Source=C:\\Users\\John\\Desktop\\location.db; Version=3; UseUTF16Encoding=True;Synchronous=Normal;New=False"; // set up the connection string
mydataConnection.Open(); // open the connection to the db
SQLiteCommand myCmd = new SQLiteCommand(); // create a new command object
myCmd.Connection = mydataConnection; // whats its connected to, see above connection string
SQLiteParameterCollection myParameters = myCmd.Parameters; // good pratice to use parameters to pass data to db
myParameters.AddWithValue("@name", testStr); //
myCmd.CommandText = "INSERT INTO location (name) VALUES (@name)";
myCmd.ExecuteNonQuery();
}
catch (SQLiteException d)
{
string myerror = "Database Error" + d;
MessageBox.Show(myerror);
}
finally // good pratice to close db connection in a finally so exceptions dont leave open.
{
mydataConnection.Close();
}
当我查看数据库/表(使用SQLite Administrator)时,字符串如下所示: áÃÃÃÃÃÃÃÃ
作为测试,我可以复制&使用SQLite Administrator将字符串直接粘贴到数据库中,并保存字符串,随后可以查看确定。
我尝试切换“UseUTF16Encoding = True;”是/否 - 没有区别。
任何想法我做错了。
答案 0 :(得分:2)
这个问题原来是我用来查看/检查数据库/数据的SQLite管理员应用程序的问题。似乎是这个应用程序在我的代码插入时无法正确显示字符。奇怪的是,如果您使用SQLite管理员应用程序直接添加测试文本(通过将测试字符串复制并粘贴到表/字段中),它将显示,保存和放大。随后查看确定。无论如何现在使用SourceForge SQLite数据库浏览器来检查我的代码是否正确写入并且所有内容都按顺序显示。
非常感谢任何花时间发表评论的人,希望这对其他人有所帮助。
答案 1 :(得分:0)
您可以尝试使用此代码
byte[] encod = Encoding.Default.GetBytes(testStr );
string result = Encoding.UTF8.GetString(encod);
myParameters.AddWithValue("@name", result);