1、在App.config中添加如下内容
<configuration>
<connectionStrings>
<add name="connstr" connectionString="server=localhost;uid=root;pwd=;Database=db_family"/>
</connectionStrings>
</configuration>
2、添加使用配置文件配置数据库的引用
添加:using System.Configuration;
3.使用ConfigurationManager取得配置文件
ConfigurationManager.ConnectionStrings[“connstr”].ConnectionString;
具体实现代码如下:
//方式一:
//string constr = "server=localhost;uid=root;pwd=;Database=db_family";
//方式二:
string constr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(constr);
conn.Open();
MySqlCommand cmd = new MySqlCommand("insert into t_family values(101,'window','Window','800*1200')", conn);
if (cmd.ExecuteNonQuery() > 0)
{
Console.WriteLine("数据库操作成功");
}
Console.ReadLine();
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
finally
{
conn.Close();
}