【发布时间】:2018-09-15 21:55:49
【问题描述】:
我正在尝试将条目插入到 Visual Studio 中的表中,但是在我运行代码然后尝试查看表后,我收到了此错误消息,
无法导入此数据库。它要么是不受支持的 SQL 服务器版本,要么是不受支持的数据库兼容性。
这是试图插入的代码,
private void doneButton_Click(object sender, EventArgs e) {
string userName = userNameTextBox.Text,
password = passwordTextBox.Text,
question = questionMenu.Text,
answer = answerTextBox.Text;
int key = EncryptionClass.generateKey();
SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyData.mdf;Integrated Security=True");
connection.Open();
String sqlQuery = "INSERT INTO dbo.Account(UserName, UserPassword, UserKey) " +
"VALUES (\'" + userName + "\', \'" + EncryptionClass.encrypt(password, key) + "\', " + key + ");";
Console.WriteLine("string " + sqlQuery);
// INSERT INTO dbo.Account(UserName, UserPassword, UserKey) VALUES ('victoramaro', 'obvmhkT1', 19);
using (SqlCommand command = new SqlCommand(sqlQuery, connection)) {
try {
var res = command.ExecuteNonQuery();
} catch (SqlException ex) {
Console.WriteLine(ex.Message);
}
}
connection.Close();
}
还有 App.config,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Assign6.Properties.Settings.MyDataConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyData.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
在 MyData.mdf 的属性中,构建操作设置为内容,复制到输出目录设置为复制(如果较新)。
在MyDataDataSet.xsd的属性中Build Action设置为None,Copy to Output Directory设置为Do not copy。
编辑
SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MyData.mdf;Integrated Security=True");
connection.Open();
String sqlQuery = "INSERT INTO dbo.Account(UserName, UserPassword, UserKey) " + //create insert query to insert user data into Account table
"VALUES (\'" + userName + "\', \'" + EncryptionClass.encrypt(password, key) + "\', " + key + ");";
using (SqlCommand command = new SqlCommand(sqlQuery, connection)) {
try {
command.ExecuteNonQuery();
string selectStatement = "SELECT * FROM Account";
SqlCommand selectCommand = new SqlCommand(selectStatement, connection);
SqlDataReader sqlReader = selectCommand.ExecuteReader(); //execute the query
while (sqlReader.Read()) { //while reader has data
string outString = string.Empty;
for (int k = 0; k < sqlReader.FieldCount; k++) { //go throught the field count
outString += String.Format("{0, -8}", sqlReader[k]); //add item to string
}
Console.WriteLine(outString);
}
}
catch (SqlException ex) {
throw ex;
}
finally {
connection.Close();
}
}
【问题讨论】:
-
总是使用参数来避免sql注入和格式化错误。
-
你是如何创建/获得
MyData.mdf的? -
项目 > 添加新项目 > 基于服务的数据库
-
其他建议:始终使用
using块和SqlConnection实例。此外,您应该只引用app.config中的连接字符串,不要将其硬编码到您的.cs文件中。 -
你的主要是什么样子的?
标签: c# sql .net winforms visual-studio