在winform c中定义Sql连接时出错

时间:2015-10-14 10:53:19

标签: c# winforms connection-string sqlconnection sqlcommand

我在app.config中编写了这段代码:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />

    </startup>
  <connectionStrings>
    <add name="localservice" providerName="System.Data.SqlClient"
          connectionString="Data Source=GROOT\SQL;Initial Catalog=localservice;Integrated Security=True" />
  </connectionStrings>

</configuration>

我的c#代码是:

using System;
using System.Configuration;
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;
using System.Data.SqlClient;

       private void button1_Click(object sender, EventArgs e)
        {

            int radius = 10;

            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["miztahrirtest2DB"].ToString());
            SqlCommand cmd = new SqlCommand("insert into vendor (username,password,lenght,width,radius,category) values (@username,@password,@lenght,@width,@radius,@category);SELECT SCOPE_IDENTITY()", con);
            cmd.Parameters.AddWithValue("username", textBox1.Text);
            cmd.Parameters.AddWithValue("password", textBox2.Text);
            cmd.Parameters.AddWithValue("lenght", Convert.ToInt32(textBox3.Text));
            cmd.Parameters.AddWithValue("width", Convert.ToInt32(textBox4.Text));
            cmd.Parameters.AddWithValue("radius", radius);
            cmd.Parameters.AddWithValue("category", comboBox1.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            //Int32 classid = Convert.ToInt32(cmd.ExecuteScalar());
            con.Close();

        }
    }
}

但是这行有一个错误:

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["miztahrirtest2DB"].ToString());

并说:

  

错误1类型或命名空间名称&#39; ConfigurationManager&#39;才不是   存在于命名空间中的System.Configuration&#39; (你错过了吗?   汇编参考?)D:\ visual studio   project \ Project \ LocalService1 \ LocalService1 \ signup.cs 35 72 LocalService1

2 个答案:

答案 0 :(得分:1)

您应该在项目中添加引用System.Configuration.dll

右键点击项目,在Add菜单中点击Reference...,然后在对话框中搜索System.Configuration.dll并点击复选框进行检查,然后点击确定。

  • 如果您使用的是VS2010,则无法搜索,您应该从.Net选项卡中选择dll
  • 如果您使用的是VS2013,则可以选择Assemblies - &gt;框架节点。

答案 1 :(得分:0)

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["localservice"].ToString());

在web.config中给出了不同的名称,但在C#中,您在 ConnectionStrings [“localservice”]

中获得了不同的名称