将C#连接到SQL Server Compact数据库
嗨,我正在尝试将SQL服务器压缩数据库连接到我的程序,我想要一个删除数据库中所有条目的按钮,当我按下该按钮时程序抛出exception并给出以下错误消息“网络相关或建立与SQL Server的连接时发生特定于实例的错误。找不到服务器或无法访问服务器。validation实例名称是否正确以及SQL Server是否配置为允许远程连接。(提供程序:SQL网络接口,错误: 26 – 找到指定的服务器/实例时出错“”
请帮忙? =]
对不起,代码在下面=]
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Data.SqlServerCe; namespace Booking_system_Final { public partial class PendingJobs : Form { SqlConnection sc = new SqlConnection("Data Source=C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf"); public PendingJobs() { InitializeComponent(); } private void PendingJobs_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'bMSDataSet.Bookings' table. You can move, or remove it, as needed. this.bookingsTableAdapter.Fill(this.bMSDataSet.Bookings); // TODO: This line of code loads data into the 'bMS_DataDataSet1.Bookings' table. You can move, or remove it, as needed. } private void button1_Click(object sender, EventArgs e) { sc.Open(); SqlCommand cmd = new SqlCommand("DELETE FROM Bookings"); cmd.Connection = sc; cmd.ExecuteNonQuery(); sc.Close(); MessageBox.Show("Database Cleared"); } } }
尝试使用SqlCeConnection
类而不是SqlConnection
:
SqlCeConnection sqlConnection1 = new SqlCeConnection(); sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf;Persist Security Info=False";
如果要连接到SQL Server Compact,请使用SqlCeConnection,SqlCeCommand等。添加对SQL Server Compact ADO.NET提供程序的引用,System.Data.SqlServerCe.dll
看看这篇博客文章: SQL SERVER – FIX:错误:(提供程序:命名管道提供程序,错误:40 – 无法打开与SQL Server的连接)
这可以逐步完成您可能需要做的事情:
简而言之:
- SQL Server应该启动并运行。
- 在SQL Server配置中启用TCP / IP
- 在Windows防火墙中打开端口
- 启用远程连接
- 启用SQL Server Browser服务
- 在防火墙中创建sqlbrowser.exe的例外
- 重新创建别名
关于每个步骤的位置和操作,您将在本文中找到更多深入的信息。
您可能还想查看SQL Server Compact的连接字符串 。 在那里,您可以找到您可以尝试使用的连接字符串的其他变体。
您似乎使用了错误的连接字符串。 (或者文件路径错误)。 查看http://www.connectionstrings.com/sql-server-ce了解连接字符串选项。