-4

im trying to insert a new row in a mssql db, but it wont be saved. Could anyone tell me what the problem is?

string connectionString = Properties.Settings.Default.DonationsConnectionString;

System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection(connectionString);

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT Donations (Name, Betrag) VALUES ('" + donator.Text + "', '" + betrag.Text + "')";
cmd.Connection = sqlConnection1;

sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
Mendax M.
  • 5
  • 1
  • 6
  • 2
    insert into i guess – RAHUL S R Feb 04 '18 at 21:22
  • 1
    Dont create SQL like that; research reserved words, a decent [SQL Tutorial](https://www.tutorialspoint.com/sql/index.htm) wouldnt hurt and read [ask] and take the [tour]. If you want help you have to provide more info such as the error message. – Ňɏssa Pøngjǣrdenlarp Feb 04 '18 at 21:22
  • 4
    Please DO NOT post samples including SQL injection. This causes discussion to be completely derailed from your actual problem and could cause downvotes as it may indicate lack of research (there is no way one who looked into how to make SQL queries to overlook parametrized queries) – Alexei Levenkov Feb 04 '18 at 21:24
  • If there are no errors then probably is https://stackoverflow.com/questions/17147249/why-saving-changes-to-a-database-fails (And do not overlook the advices about sql injection) – Steve Feb 04 '18 at 21:50
  • Please describe "it wont be saved." Are you saying that you execute the statement, nothing gets inserted, and no exception occurs? – Scott Hannen Feb 04 '18 at 23:08
  • Yes, please post the actual error. In addition, you need to capture the actual SQL you are sending to the server that fails ... because you are building it with variables, we can't really know what it is (although it looks like there is an easy answer). Consider bulding your .CommandText into a variable, then debug and catch the value of the variable and try to fix the SQL in a query editor like SSMS. Then if you can't fix it, make your question specifically about that SQL. – Mike M Feb 04 '18 at 23:30

1 Answers1

0

I think u forgot "INTO" of the insert sql syntax

cmd.CommandText = "INSERT INTO Donations (Name, Betrag) VALUES ('" + donator.Text + "', '" + betrag.Text + "')";

but i recommend u to change like this

cmd.CommandText = "INSERT INTO Donations (Name, Betrag) VALUES(@donator_temp,@betrag_temp);

cmd.Parameters.Add("@donator_temp", donator.text);
cmd.Parameters.Add("@betrag_temp", betrag.text);

cmd.ExecuteNonQuery();
Lemons
  • 107
  • 1
  • 13