Ich habe gerade ein Problem, das ich zu beheben versuche. Ich habe gerade versucht, auf eine Datenbank zuzugreifen und mit Hilfe von C # einige Werte einzufügen.
Die Dinge, die ich ausprobiert habe
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
Eine neue Zeile wurde eingefügt und alles hat gut funktioniert. Jetzt habe ich versucht, eine Zeile mit Variablen einzufügen:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id, @username, @password, @email)";
command.Parameters.AddWithValue("@id","abc")
command.Parameters.AddWithValue("@username","abc")
command.Parameters.AddWithValue("@password","abc")
command.Parameters.AddWithValue("@email","abc")
command.ExecuteNonQuery();
Hat nicht funktioniert, es wurden keine Werte eingefügt. Ich habe noch etwas versucht
command.Parameters.AddWithValue("@id", SqlDbType.NChar);
command.Parameters["@id"].Value = "abc";
command.Parameters.AddWithValue("@username", SqlDbType.NChar);
command.Parameters["@username"].Value = "abc";
command.Parameters.AddWithValue("@password", SqlDbType.NChar);
command.Parameters["@password"].Value = "abc";
command.Parameters.AddWithValue("@email", SqlDbType.NChar);
command.Parameters["@email"].Value = "abc";
command.ExecuteNonQuery();
Kann mir jemand sagen, was ich falsch mache?
Mit freundlichen Grüßen
BEARBEITEN:
in einer anderen Zeile habe ich einen neuen SQL-Befehl erstellt
var cmd = new SqlCommand(query, connection);
Funktioniert immer noch nicht und ich kann im obigen Code nichts falsch finden.
Ich gehe davon aus, dass Sie eine Verbindung zu Ihrer Datenbank haben und die Einfügeparameter nicht mit c # ausführen können.
Sie fügen die Parameter nicht in Ihre Abfrage ein. Es sollte so aussehen:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");
command.ExecuteNonQuery();
Aktualisierte:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@id", "abc");
command.Parameters.AddWithValue("@username", "abc");
command.Parameters.AddWithValue("@password", "abc");
command.Parameters.AddWithValue("@email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Versuchen
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username, @password, @email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("@id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("@username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("@password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("@email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
Der häufigste Fehler (vor allem bei der Verwendung von Express) für "Meine Einfügung ist nicht aufgetreten" ist: in der falschen Datei suchen.
Wenn Sie dateibasiertes Express verwenden (und nicht fest verbunden), dann ist die Datei in Ihrem Projektordner (beispielsweise c:\dev\myproject\mydb.mbd
) nicht die Datei, die in Ihrem Programm verwendet wird. Beim Erstellen wird diese Datei kopiert - zum Beispiel in c:\dev\myproject\bin\debug\mydb.mbd
; Ihr Programm wird im Kontext von c:\dev\myproject\bin\debug\
ausgeführt. Daher müssen Sie hier prüfen, ob die Bearbeitung tatsächlich stattgefunden hat. Um sicher zu gehen, fragen Sie nach den Daten in der Anwendung (nach dem Einfügen).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Ich habe gerade eine wiederverwendbare Methode dafür geschrieben, hier gibt es keine Antwort mit wiederverwendbarer Methode.
hier ist der Code aus meinem aktuellen Projekt:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;[email protected]";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}