C# Sql 连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19794971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Sql Connection String
提问by Justin Montego
I'm a 17 year old software engineering student and am having trouble with linking my sql database to my C# Win App. I was able to accomplish this task using a access database but the database needs to be in SQL. Any Help would be greatly appreciated! The code i have so far is :
我是一名 17 岁的软件工程专业的学生,在将我的 sql 数据库链接到我的 C# Win App 时遇到了问题。我能够使用访问数据库完成此任务,但数据库需要在 SQL 中。任何帮助将不胜感激!我到目前为止的代码是:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb; // all Non-SqlServer Databases ie oracle, access, sqlLite
using System.Configuration;
namespace SqlWinApp
{
public partial class Form1 : Form
{
// Declare and init data objects
// Connect to an external data source
//OleDbConnection cnDataCon =
// new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=H:/SEWD/ASP/dataTestJr/App_Data/dbWaxStax.accdb");
SqlConnection cnDataCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["cnExternalData"].ConnectionString);
// dataset: Container object for data tables
DataSet dsData = new DataSet();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
cnDataCon.Open();
{
loadDdlTitles();
}
}
catch (Exception errDesc)
{
string strMsgError = "Error encountered on open: " + errDesc.Message.ToString().Replace('\'', ' ');
MessageBox.Show(@"<script language='javascript'>alert('" + strMsgError + "')</script>");
MessageBox.Show(@"<script language='javascript'>alert('Application will terminate')</script>");
return;
}
}
private void loadDdlTitles()
{
//Response.Write(@"<script language='javascript'>alert('loadDDlTitles')</script>");
// store sql into a string in order to be utilized at a later time.
string strSqlTitles = "SELECT * FROM tblTitles ORDER BY title";
// data adapters act as data filters
OleDbDataAdapter daTitles = new OleDbDataAdapter();
// command syncs the data source with the filter (data sdapter) and readies it for instantiation
OleDbCommand cmNameTitles = new OleDbCommand(strSqlTitles, cnDataCon);
// select command syncs the filter with the data
daTitles.SelectCommand = cmNameTitles;
try
{
daTitles.Fill(dsData, "tblTitlesInternal"); // blow pt.
}
catch (Exception errDesc)
{
string strMsgError = "Error encountered in data adapter object: " + errDesc.Message.ToString().Replace('\'', ' ');
MessageBox.Show(@"<script language='javascript'>alert('" + strMsgError + "')</script>");
MessageBox.Show(@"<script language='javascript'>alert('Application will terminate')</script>");
}
// Connect control obj to datasource and populate
ddlTitle.DataSource = dsData.Tables["tblTitlesInternal"];
ddlTitle.DisplayMember = "nameTitle";
ddlTitle.ValueMember = "nameTitlesID";
}
}
}
In my App.config i have:
在我的 App.config 我有:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="cnExternalData" connectionString="Data Source=|DataDirectory|215-6576.All-Purpose Handyman.dbo; Provider=Microsoft.ACE.OLEDB.12.0" />
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Data Source=215-6576;User ID=sa"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Finally, My database is named 215-6576.All-PurposeHandyman.dbo and the table i am using is named tblTitles. Any help again would be greatly appreciated! Thank you!
最后,我的数据库名为 215-6576.All-PurposeHandyman.dbo,我使用的表名为 tblTitles。任何帮助将不胜感激!谢谢!
采纳答案by Sven Grosen
An invaluable website I've gone to repeatedly is ConnectionStrings.com.
我反复访问的一个非常宝贵的网站是ConnectionStrings.com。
Assuming everything you already have is correct, you just need to modify your SQL connection string in the config file:
假设你已经拥有的一切都是正确的,你只需要在配置文件中修改你的 SQL 连接字符串:
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Server=215-6576;User ID=sa; Database=All-PurposeHandyman; Password=password"
providerName="System.Data.SqlClient" />
If your sa account has a password, you will need to provide that as well via "Password=[Password]" in that same connectionString attribute.
如果您的 sa 帐户有密码,则您还需要通过同一 connectionString 属性中的“Password=[Password]”来提供该密码。
EDIT
编辑
In your C# code, you don't need the braces around your call to loadDdlTitles();
, you can safely remove those.
在您的 C# 代码中,您不需要调用 的大括号loadDdlTitles();
,您可以安全地删除它们。
EDIT2
编辑2
Added password attribute into modified connection string to make clear how it should work.
在修改后的连接字符串中添加了密码属性,以明确它应该如何工作。
回答by David
You need to have the server/machine name in the connection string. This link has some information and examples to use:
您需要在连接字符串中包含服务器/机器名称。此链接有一些信息和示例可供使用:
http://msdn.microsoft.com/en-us/library/jj653752%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/jj653752%28v=vs.110%29.aspx
回答by AllenG
Well, I see 3 problems just off the bat (and there might be more if I looked more closely). The two that are causing you trouble are:
好吧,我马上就看到了 3 个问题(如果我仔细观察,可能还会有更多问题)。给你带来麻烦的两个是:
- You're still calling your Access connection string
- Your SQL connection string is formatted incorrectly.
- 您仍在调用您的 Access 连接字符串
- 您的 SQL 连接字符串格式不正确。
The third problem isn't major, but it'll be annoying when you go to fix #1: your connection string name is really long.
第三个问题不是主要的,但是当你去修复 #1 时它会很烦人:你的连接字符串名称真的很长。
Modify your sql connection string thusly:
如此修改您的 sql 连接字符串:
<add name = "SqlConnection" connectionString="[yourConnectionStringHere]" />
Then modify your calling code:
然后修改您的调用代码:
SqlConnection cnDataCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString);
For the specific connection string, I recommend heading to http://connectionstrings.comand taking a look. But it will be something like this:
对于特定的连接字符串,我建议前往http://connectionstrings.com并查看。但它会是这样的:
Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;