[英]How do i store data in a service-based database?
我正在嘗試將用戶名和密碼存儲在基於服務的數據庫中的名為“ User”的表中。
下面是我嘗試過的代碼。
private void Btn_register_Click(object sender, RoutedEventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\CUC-SRV-FS02\Studio-StuHome$\13mihailovs.m\Documents\IT_Unit4\IT_Unit4\ITUnit4.mdf;Integrated Security=True");
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into User(Username, Password) " +
"values(@Username, @Password)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("@Username", txt_username.Text);
com.Parameters.AddWithValue("@Password", txt_password.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
MessageBox.Show("error has occured");
}
}
在Ado.Net中插入數據庫的正確方法:
private readonly SqlConnection _con = new SqlConnection("Data Source=.;Initial
Catalog=dbPhoneBook;Integrated Security=True");
public string Add(string user , string pass)
{
string result = "";
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = _con;
cmd.CommandText = "insert into tbl_login(user,pass)values(@user,@pass)";
cmd.Parameters.AddWithValue("@user", user);
cmd.Parameters.AddWithValue("@pass", pass);
if (_con.State != ConnectionState.Open)
{
_con.Open();
}
cmd.ExecuteNonQuery();
result = "Ok";
cmd.Dispose();
}
catch
{
cmd.Dispose();
result = "NOk";
}
return result;
}
還要檢查以下內容。檢出網站https://www.connectionstrings.com/到數據庫的鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.