2011-10-20 84 views
3

所以,我有一個用於連接和插入一條記錄到數據庫中下面的代碼:無法連接到本地數據庫在C#

string dbfile = "|DataDirectory|\\Databases\\Database.sdf"; 
      SqlConnection connection = new SqlConnection("Data Source=" + dbfile); 
      SqlCommand query = new SqlCommand("insert into Leggers values('" + leggernummer + "','" + omschrijving + "')", connection); 
      ** connection.Open(); ** 
      query.BeginExecuteNonQuery(); 

      connection.Close(); 

我的配置文件看起來像這樣:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
    </configSections> 
    <connectionStrings> 
     <add name="connectionstring" 
      connectionString="Data Source=|DataDirectory|\Databases\Database.sdf" 
      providerName="Microsoft.SqlServerCe.Client.3.5" /> 
    </connectionStrings> 
</configuration> 

然後它在第一個代碼塊中的**和**之間出現錯誤

錯誤是:

System.Data.SqlClient.SqlException was unhandled 
    Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) 
    Source=.Net SqlClient Data Provider 
    ErrorCode=-2146232060 
    Class=20 
    LineNumber=0 
    Number=-1 
    Server="" 
    State=0 
    StackTrace: 
     at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) 
     at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() 
     at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity) 
     at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) 
     at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) 
     at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) 
     at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) 
     at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) 
     at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) 
     at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) 
     at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) 
     at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) 
     at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) 
     at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) 
     at System.Data.SqlClient.SqlConnection.Open() 
     at Stockbeheer_Savenay.Forms.LeggerToevoegen.addItem(String leggernummer, String omschrijving) in C:\Users\Simon\Desktop\Stockbeheer Savenay\Stockbeheer Savenay\Forms\LeggerToevoegen.cs:line 59 
     at Stockbeheer_Savenay.Forms.LeggerToevoegen.btnToevoegen_Click(Object sender, EventArgs e) in C:\Users\Simon\Desktop\Stockbeheer Savenay\Stockbeheer Savenay\Forms\LeggerToevoegen.cs:line 31 
     at System.Windows.Forms.Control.OnClick(EventArgs e) 
     at System.Windows.Forms.Button.OnClick(EventArgs e) 
     at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 
     at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 
     at System.Windows.Forms.Control.WndProc(Message& m) 
     at System.Windows.Forms.ButtonBase.WndProc(Message& m) 
     at System.Windows.Forms.Button.WndProc(Message& m) 
     at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 
     at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 
     at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 
     at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) 
     at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) 
     at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) 
     at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) 
     at System.Windows.Forms.Application.Run(Form mainForm) 
     at Stockbeheer_Savenay.Program.Main() in C:\Users\Simon\Desktop\Stockbeheer Savenay\Stockbeheer Savenay\Classes\Program.cs:line 18 
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: 

我是C#數據庫的新手,所以我不確定出了什麼問題。試圖遵循教程,但他們都說不同的事情,所以很難弄清楚我應該做什麼。

謝謝!

+0

你可以連接到數據庫通過SQL Server管理Studi Ø?如果是這樣,您使用什麼信息進行連接,並且一旦連接,您的數據庫是否可訪問?那個DB的名字是什麼?我想我們只需要在這裏調試連接字符串...... –

+0

SQLEXPRESS服務實例是否正在運行? – kprobst

+0

@ MerlynMorgan-Graham:我不確定SQL Server Management Studio是什麼。我在Visual Studio中創建了數據庫,並且在那裏進行連接,我測試過了。數據庫的名稱就是「數據庫」。 –

回答

10

當使用.sdf文件(SQL服務器精簡版),你需要使用SqlCeConnectionSqlConnection(即針對一個完整的SQL Server的工作原理):也

string dbfile = "|DataDirectory|\\Databases\\Database.sdf"; 

string insertStmt = "insert into Leggers values('" + leggernummer + "','" + omschrijving + "')"; 

using(SqlCeConnection connection = new SqlCeConnection("Data Source=" + dbfile)) 
using(SqlCeCommand query = new SqlCeCommand(insertStmt, connection)) 
{ 
    connection.Open(); 
    query.BeginExecuteNonQuery(); 
    connection.Close(); 
} 

:你應該嘗試使用參數化查詢,而不只是連接在一起你的SQL語句......(研究「SQL注入攻擊」....)

+0

它不能識別SqlCeConnection和SqlCeCommand。我有以下使用指令:using System.Data; using System.Data.SqlClient; using System.Data.OleDb; 此外:該程序是一個離線應用程序,只有1人將使用。所以我沒有SQL注入的風險。 –

+0

好的,現在得到了連接。但是,我的數據庫沒有更新我添加的新記錄。 –

+0

或者它只是忽略添加了什麼,因爲我正在調試? (對不起,三人發帖,到後期編輯) –

相關問題