【问题标题】:Null connection - Connecting to ASP.NET - Microsoft SQL Server空连接 - 连接到 ASP.NET - Microsoft SQL Server
【发布时间】:2013-06-28 09:20:32
【问题描述】:

我一直在尝试连接到数据库,但它显示“null”错误。 所以, 我尝试打开之前练习的表格,结果非常好。

这是我的代码:

string username = txtusername.Text;
        string firstname = txtfirstname.Text;
        string lastname = txtlastname.Text;
        string email = txtemail.Text;
        string password = txtpass.Text;
        string gender = rbgender.Text;
        string nationality = dcountry.Text;
        string phone = txtphone.Text;

        string connection = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
        SqlConnection connect = new SqlConnection(connection);
        string command = "INSERT INTO Persons(username, firstname, lastname, email, password, gender, nationality, phone) VALUES('@username','@firstname','@lastname','@email','@password','@gender','@nationality','@phone')";


        SqlCommand insert = new SqlCommand(command +","+ connection);
        insert.Parameters.AddWithValue("@username", username);
        insert.Parameters.AddWithValue("@firstname", firstname);
        insert.Parameters.AddWithValue("@lastname", lastname);
        insert.Parameters.AddWithValue("@email", email);
        insert.Parameters.AddWithValue("@password", password);
        insert.Parameters.AddWithValue("@gender", gender);
        insert.Parameters.AddWithValue("@nationality", nationality);
        insert.Parameters.AddWithValue("@phone", phone);
        insert.ExecuteNonQuery();
        connect.Close();

和web.config中的connectionstrings有关系吗?

 <connectionStrings>
<add name="ApplicationServices"
     connectionString="Data Source=ADRIAN-LAPTOP\SQL;Initial Catalog=New;Integrated Security=True"
     providerName="System.Data.SqlClient" />

【问题讨论】:

  • 请告诉我们您到底面临什么异常。
  • 你可以添加一个try catch,然后处理异常,因为更容易知道到底发生了什么。
  • 除了别人已经说过的,SqlCommand insert = new SqlCommand(command +","+ connection);应该是SqlCommand insert = new SqlCommand(command, connection);。或者更好的是,将其包裹在 using(...) { ... } 中。

标签: c# asp.net sql-server connection-string


【解决方案1】:

web.config 文件中的键与在代码中使用的不同。

应该是,

string connection = ConfigurationManager.ConnectionStrings["ApplicationServices"]
                                        .ConnectionString;

并且无需将参数名称用单引号括起来。

 string command = @"
   INSERT INTO Persons
      (username, firstname, lastname, email, password, gender, nationality,phone) 
     VALUES
      (@username,@firstname,@lastname,@email,@password,@gender,@nationality,@phone)";

附带说明,始终使用using 语句(或调用Dispose())来处理ADO 资源。

using(SqlConnection connect = new SqlConnection(connectionString))
 {
  //
 }

【讨论】:

  • 哇,谢谢。我还注意到(我实际上收到了一个错误)我忘记打开连接。 XD
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
  • 2018-10-26
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多