嗨我想从本地SQL服务数据库获取数据以从用户注册表单中获取输入。但是当我按下它没有记录到可服务数据库的按钮时。C#使用SQL登录应用程序
我需要使用执行非查询吗?我将如何解决这个代码?感谢
using System.Data.Sql;
using System.Data.SqlClient;
namespace Paddle_Power
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
try
{
cn.Open();
MessageBox.Show("open");
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
string username = textBox1.Text;
string password = textBox2.Text;
string sqlquery = ("SELECT * FROM User WHERE Username = '" + textBox1.Text + "'");
sqlquery = "INSERT INTO [User] (Username, Password) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("Username", username);
command.Parameters.AddWithValue("Password", password);
command.Parameters.Clear();
}
}
}
你为什么分配给sqlquery,然后立即重新分配?你为什么不执行SQL?你没有正确使用参数...你有没有试过一个教程? –
是的,我从一个教程得到了这个,但它有很多负面评论说同样的事情。你能帮我重新写这个吗? – stefan
如果您不忽略抛出哪个异常,它可能也会帮助您排除故障。没有try/catch块,你会做得更好。 –