C# 空连接-连接到ASP.NET-Microsoft SQL Server
我一直在尝试连接到数据库,但它显示“null”错误。 所以 我试着打开我练习的前一张表格,结果是非常好的 这是我的代码:C# 空连接-连接到ASP.NET-Microsoft SQL Server,c#,asp.net,sql-server,connection-string,C#,Asp.net,Sql Server,Connection String,我一直在尝试连接到数据库,但它显示“null”错误。 所以 我试着打开我练习的前一张表格,结果是非常好的 这是我的代码: string username = txtusername.Text; string firstname = txtfirstname.Text; string lastname = txtlastname.Text; string email = txtemail.Text; string password =
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中的ConnectionString有关
<connectionStrings>
<add name="ApplicationServices"
connectionString="Data Source=ADRIAN-LAPTOP\SQL;Initial Catalog=New;Integrated Security=True"
providerName="System.Data.SqlClient" />
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)";
请注意,始终通过使用语句或调用dispose来处置ADO资源
请让我们知道您正面临什么样的异常。您能否添加一个try-catch,并接受异常,因为这样更容易知道到底发生了什么。除了其他人已经说过的以外,SqlCommand-insert=new-SqlCommandcommand+,+connection;应为SqlCommand insert=new SqlCommandcommand,connection;。或者更好的是,用。。。{…}哇,谢谢你。我还注意到我实际上收到了一个错误,我忘记打开连接。除息的
using(SqlConnection connect = new SqlConnection(connectionString))
{
//
}