如何创建连接文件 [英] How to create a connection file
本文介绍了如何创建连接文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下面的代码连接到数据库
string connString = @Data source = test2; Database = test1data; User Id = a; Password = test1234 ;
using(SqlConnection sqlConn = new SqlConnection(connString))
{
string sqlQuery = @SELECT * from Zone;
SqlCommand cmd = new SqlCommand(sqlQuery,sqlConn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
dataGridView1.DataSource = new BindingSource(table,null);
}
但是我想创建一个可以更改的连接文件。
例如:
我正在连接数据库,但更改此文件我将连接到另一个数据库
我尝试过:
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings [测试]的ConnectionString。
// ConfigurationManager.ConnectionStrings [testdb]。ConnectionString;
using(SqlConnection sqlConn = new SqlConnection(connectionString))
{
string sqlQuery = @SELECT * from Zone;
SqlCommand cmd = new SqlCommand(sqlQuery,sqlConn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
dataGridView1.DataSource = new BindingSource(table,null);
}
这是我在app.config中尝试的代码
< ; add name =testconnectionString =Data Source = .; Initial Catalog = test1data; User Id = a; Password = test123providerName =System.Data.SqlClient/>
解决方案
这将告诉你如何:如何:保存和编辑连接字符串 [ ^ ]
更新:这是一篇CodeProject文章,向您展示如何在代码中执行此操作:将连接字符串保存到app.config [ ^ ]
I am connecting to the database with the code below
string connString = @"Data source = test2 ; Database=test1data ; User Id=a ; Password=test1234"; using (SqlConnection sqlConn = new SqlConnection(connString)) { string sqlQuery = @"SELECT * from Zone"; SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable table = new DataTable(); da.Fill(table); dataGridView1.DataSource = new BindingSource(table, null); }
But I wanted to create a file to connect that could be changed.
For example:
I'm connecting to a database, but changing this file I'll connect to another database
What I have tried:
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["test"].ConnectionString; // ConfigurationManager.ConnectionStrings["testdb"].ConnectionString; using (SqlConnection sqlConn = new SqlConnection(connectionString)) { string sqlQuery = @"SELECT * from Zone"; SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable table = new DataTable(); da.Fill(table); dataGridView1.DataSource = new BindingSource(table, null); }
And this is the code i tryed in app.config
<add name="test" connectionString="Data Source=.;Initial Catalog=test1data; User Id=a ; Password=test123" providerName="System.Data.SqlClient" />
解决方案
This will show you how: How to: Save and Edit Connection Strings[^]
Update: Here is a CodeProject article that show you how to do it in code: Saving Connection Strings to app.config[^]
这篇关于如何创建连接文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文