[英]visual studio C# connect textbox to database
我已經在c#VS 2010中編寫了此簡單代碼,用於存儲名稱並登錄到本地表。 當我跑步時,向我顯示此按摩:
“ nvarchar附近的語法不正確”
using System;
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string name =textBox1.Text;
string login =textBox2 .Text;
string sqlquery;
SqlConnection cn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename= C:\\Users\\Safeen\\Documents\\Visual Studio 2010\\Projects\\WindowsFormsApplication12\\WindowsFormsApplication12\\Database1.mdf;Integrated Security=True;User Instance=True");
cn.Open();
sqlquery = "INSERT INTO Table1 (user, password) VALUES ('" + name + "','" + login + "')";
try
{
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("@user ", textBox1.Text);
command.Parameters.AddWithValue("@password ", textBox2.Text);
command.ExecuteNonQuery();
MessageBox.Show("Table1 Added");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
textBox1.Clear();
textBox2.Clear();
cn.Close();
}
}
您正在為參數提供多個值。
您說的是user = name
和password = login
的db值,然后ALSO傳入了兩個參數@user
和@password
,而沒有告訴SQL哪個設置正確。
您肯定要使用SqlCommand
選項,並將SqlCommand.CommandType
設置為正確的值。 這樣分配參數是安全的。 直接將變量放到VALUES()
子句中(就像您在原始帖子中一樣)可以使您容易受到SQL Injection攻擊。
我在這里編輯了使用存儲過程的建議。 根據評論中的少量討論,這更多是我個人的偏愛。 我喜歡分離我的數據庫層。 同樣,這意味着如果有任何更改,您只需要更新一次存儲過程,而不是在應用程序中可能存在的任何地方查找查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.