Null连接-正在连接到ASP.NET-Microsoft SQL Server
本文关键字:连接 NET-Microsoft SQL Server ASP Null | 更新日期: 2023-09-27 18:20:19
我一直在尝试连接到数据库,但它显示"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>
<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)";
附带说明一下,总是使用using语句(或调用Dispose()
)来处理ADO资源。
using(SqlConnection connect = new SqlConnection(connectionString))
{
//
}