![](/img/trans.png)
[英]How do I connect to SQL Server using OLEDB using Windows Authentication connection string
[英]How do I define a connection string to connect to SQL Server from a Windows application?
我是ASP.NET Web開發人員。 我創建了一個Windows應用程序,用於從SQL Server檢索數據。 這是我的應用程序配置和類文件,用於從SQL Server檢索數據:
App.config中
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<appSettings>
</appSettings>
<connectionStrings>
<add name="ConnString" connectionString="Data Source=INFY\SQLEXPRESS;Initial Catalog=NEWBULKSMS;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
嘗試連接到SQL Server的代碼
using System;
using System.Collections.Generic;
using System.Collections;
using MySql.Data.MySqlClient;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public class Mysql
{
public static string ConString = System.Configuration.ConfigurationManager.AppSettings.Get("ConnString");
public static string InsertResult = "0";
private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());
private static MySqlParameter[] DiscoverSpParameterSet(string spName, bool includeReturnValueParameter)
{
using (MySqlConnection cn = new MySqlConnection(Mysql.ConString))
{
using (MySqlCommand cmd = new MySqlCommand(spName, cn))
{
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
MySqlCommandBuilder.DeriveParameters(cmd);
MySqlParameter[] discoveredParameters = new MySqlParameter[cmd.Parameters.Count]; ;
cmd.Parameters.CopyTo(discoveredParameters, 0);
return discoveredParameters;
}
}
}
}
這是連接到SQL Server數據庫的正確方法嗎?
您的連接字符串看起來不錯,但是您的代碼正在嘗試使用MySql類連接到SQL Server。 錯了 您應該使用SqlConnection
代替MySqlConnection
,而不是MySqlCommand
- SqlCommand
等等。
所有以MySql
開頭的類都屬於MySql.Data.MySqlClient
命名空間,旨在與MySql一起使用。
要使用Sql Server,您需要使用以Sql
開頭並屬於System.Data.SqlClient
命名空間的類。
我將從刪除using MySql.Data.MySqlClient;
代碼頂部的第二行,然后通過將MySql類替換為Sql Server類來修復所有編譯錯誤。
像下面這樣更改連接字符串,您必須從MySql更改為SQL並使用System.Data.SqlClient進行添加,而要使用已經在項目中添加的MySql.Data.MySqlClient ...... .....
public static string connectionString = WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
public static string InsertResult = "0";
private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());
private static SqlParameter[] DiscoverSpParameterSet(string spName, bool includeReturnValueParameter)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(spName, sqlConnection))
{
connection.Open();
command.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(command);
SqlParameter[] discoveredParameters = new SqlParameter[cmcommandd.Parameters.Count];
discoveredParameters=command.ExecuteNonQuery();
ccommandn.Close();
return discoveredParameters;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.