我正在使用C#和本地数据库(An empty SQL Server Compact Edition database for local data
)
但是我无法连接到数据库并获取数据。
这是我尝试的方法:
// Properties.Settings.Default.DatabaseConnectionString = Data Source=|DataDirectory|\Database.sdf
// I guess Visual Studio put it there after I created my database...
using(SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.DatabaseConnectionString)) {
using(SqlCommand sqlCommand = new SqlCommand("SELECT * FROM users WHERE id = @id", sqlConnection)) {
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("@id", 1);
try {
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader(CommandBehavior.SingleRow);
if(reader.Read()) {
System.Console.WriteLine(reader);
System.Console.WriteLine(reader["id"]);
System.Console.WriteLine(reader["name"]);
}
}
catch(Exception e) {
System.Console.WriteLine(e.GetBaseException());
}
finally {
sqlConnection.Close();
}
}
}
我的整个程序挂了一段时间,暂停后我收到以下消息:
建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称正确,并且已将SQL Server配置为允许远程连接。(提供者:SQL网络接口,错误:26-指定服务器/实例时出错)
我正在使用C#和本地数据库(用于本地数据的空SQL Server Compact Edition数据库)
您使用的是Sql Server Compact
文件,而不是Sql Server Local DB
要处理Sql Server Compact,您需要使用System.Data.SqlServerCe
名称空间,而不是System.Data.SqlServer
。
替换SqlConnection
,SqlCommand
...
随着SqlceConnection
,SqlCeCommand
...
并且Sql Server Compact不支持存储过程(如何在SqlCE中使用存储过程),因此sqlCeCommand.CommandType
不能CommandType.StoredProcedure
。
您需要将commandType.Text与命令参数一起使用。
using(SqlCeConnection sqlCeConnection = new SqlCeConnection(Properties.Settings.Default.DatabaseConnectionString)) {
using(SqlCeCommand sqlCeCommand = new SqlCeCommand("SELECT * FROM users WHERE id = @id", sqlCeConnection)) {
sqlCeCommand.CommandType = CommandType.Text;
sqlCeCommand.Parameters.AddWithValue("@id", 1);
try {
sqlCeConnection.Open();
SqlCeDataReader reader = sqlCeCommand.ExecuteReader(CommandBehavior.SingleRow);
if(reader.Read()) {
System.Console.WriteLine(reader);
System.Console.WriteLine(reader["id"]);
System.Console.WriteLine(reader["name"]);
}
}
catch(Exception e) {
System.Console.WriteLine(e.GetBaseException());
}
finally {
sqlCeConnection.Close();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句