Bel*_*lga 0 c# sql-server asp.net connection-string
我一直在尝试连接数据库,但它显示'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();
Run Code Online (Sandbox Code Playgroud)
它与web.config中的连接字符串有什么关系吗?
<connectionStrings>
<add name="ApplicationServices"
connectionString="Data Source=ADRIAN-LAPTOP\SQL;Initial Catalog=New;Integrated Security=True"
providerName="System.Data.SqlClient" />
Run Code Online (Sandbox Code Playgroud)
密钥web.config文件不同,然后在代码中使用.
它应该是,
string connection = ConfigurationManager.ConnectionStrings["ApplicationServices"]
.ConnectionString;
Run Code Online (Sandbox Code Playgroud)
并且无需在单引号中包装参数名称.
string command = @"
INSERT INTO Persons
(username, firstname, lastname, email, password, gender, nationality,phone)
VALUES
(@username,@firstname,@lastname,@email,@password,@gender,@nationality,@phone)";
Run Code Online (Sandbox Code Playgroud)
附注,始终使用using语句(或调用Dispose())来处置ADO资源.
using(SqlConnection connect = new SqlConnection(connectionString))
{
//
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
464 次 |
| 最近记录: |