我是 C# 到 SQL 交互的新手,如果这里的问题很明显或重复,我深表歉意。我正在尝试在表'Clientes'中插入一个新行,此代码的第一部分连接到数据库,然后检查表中是否存在重复项,我知道这些部分有效。我包括它以防万一问题可能来自我的连接字符串或其他东西。
一旦它到达 Try Catch,它就会抛出我放在那里的“错误”消息,所以我知道插入时发生了故障。通常我可以根据错误消息中的信息来解决这样的问题,但这只会
在输出选项卡中给我
[Exception throw: 'System.Data.SqlClient.SqlException' in System.Data.dll]
,错误中没有任何内容列表,我找不到更多详细信息,而且我无法根据类似的 SO 帖子推断出问题。
if ( textBox_tel.Text.All(c => char.IsDigit(c))) //checks no letters in phone number
{
string connectionstring;
SqlConnection con;
connectionstring = @"Data Source = DRAGONSLAYER;Initial Catalog=bancodb;User id=bancodb_admin;Password=admin";
con = new SqlConnection(connectionstring);
con.Open(); //now connected to the DB
string querysignupsubmitcheck = "Select * from Clientes Where Login = '" + textBox_usr.Text + "'";
SqlDataAdapter sda_signupsubmitcheck = new SqlDataAdapter(querysignupsubmitcheck, con);
DataTable dtbl_signupsubmitcheck = new DataTable();
sda_signupsubmitcheck.Fill(dtbl_signupsubmitcheck);
con.Close();
if (dtbl_signupsubmitcheck.Rows.Count < 1) //checks the new client row isn't a duplicate
{
try
{
string querysignupsubmit = "Insert into Clientes (Nombre, Telefono, Login, Password) Values (" +
textBox_name.Text + ", " +
textBox_tel.Text + ", " +
textBox_usr.Text + ", " +
textBox_pword2.Text + ")";
SqlCommand sc_signupsubmitc = new SqlCommand(querysignupsubmit, con);
sc_signupsubmitc.ExecuteNonQuery();
this.Close();
objform_login.Show();
}
catch { label_alert.Text = "ERROR DE BASE DE DATOS"; }
}
else
{
label_alert.Text = "usuario ya existe";
}
}
else
{
label_alert.Text = "Telefono acepta solo numeros";
}
根据此处另一个问题的建议,我将 try-catch 语句中的代码更改为此,但它仍然引发相同的异常:
using (con)
{
string querysignupsubmit = "INSERT INTO Clientes (Nombre, Telefono, Login, Password) VALUES (@val1, @val2, @val3, @val4)";
using (SqlCommand sc_signupsubmit = new SqlCommand())
{
sc_signupsubmit.Connection = con;
sc_signupsubmit.CommandText = querysignupsubmit;
sc_signupsubmit.Parameters.AddWithValue("@val1", textBox_name.Text);
sc_signupsubmit.Parameters.AddWithValue("@val1", textBox_tel.Text);
sc_signupsubmit.Parameters.AddWithValue("@val1", textBox_usr.Text);
sc_signupsubmit.Parameters.AddWithValue("@val1", textBox_pword2.Text);
con.Open();
sc_signupsubmit.ExecuteNonQuery();
con.Close();
this.Close();
objform_login.Show();
}
}
感谢您提供任何帮助或建议,这是我要插入的表的代码:
CREATE TABLE [dbo].[Clientes] (
[ClienteID] INT IDENTITY (1, 1) NOT NULL,
[Nombre] VARCHAR (255) NOT NULL,
[Telefono] VARCHAR (20) NOT NULL,
[Login] VARCHAR (255) DEFAULT ('default_login') NOT NULL,
[Password] VARCHAR (128) NOT NULL,
CONSTRAINT [PK_Clientes] PRIMARY KEY CLUSTERED ([ClienteID] ASC)
);
EDIT2:我很笨,多次宣布 Val1,很笨。谢谢大家的帮助。