C# code to insert values into a database not working - c#

This is the button for inserting those fileds into my database, the field names and db connection works for any other tasks but somehow this button keeps telling me the insert failed"
private void button1_Click(object sender, EventArgs e)
{
try {
int answer;
sql = "INSERT INTO Registration VALUES (#Student_ID,#Course_ID,#Section,#Start_Date,#End_Date,#Semester)";
connection.Open();
command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#Student_ID", comboBox1.SelectedItem.ToString());
command.Parameters.AddWithValue("#Course_ID", lstcourse.SelectedItem.ToString());
command.Parameters.AddWithValue("#Section", txtsection.Text);
command.Parameters.AddWithValue("#Start_Date", txtstart.Text);
command.Parameters.AddWithValue("#End_Date", txtend.Text);
command.Parameters.AddWithValue("#Semester", txtsemester.Text);
answer = command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("You're awesome and added " + answer + " row to your registration");
}
catch
{
MessageBox.Show("You screwed up");
}
/////////////////////////////////
}
This is the table:
Registration_ID float Checked
Student_ID float Checked
Course_ID float Checked
Section float Checked
Start_Date datetime Checked
End_Date datetime Checked
Semester nvarchar(255) Checked
Unchecked

Somehow this button keeps telling me the insert failed
It would of been helpful if you could have posted the actual error from the catch statement. If you debugged the routine and specifically inspected the error message, you'd notice what was wrong.
The primary issue of the error is because you didn't supply the columns to insert into. If you supplied all columns upfront the insert statement would be satisfied and work just fine.
Solution
Either make sure all columns are accounted for in the insert statement.
Specify the columns you are inserting into.
Your table according to your post has 7 columns, you are only supplying 6 of them. When you using the syntax of INSERT INTO TABLENAME VALUES() you have to supply values for all columns, not just a select few.
On the other hand if you used the syntax of INSERT INTO TABLENAME(columnName, columnName)VALUES(value, value) you are fulfilling the requirements by supplying two columns along with their values.
Side Note:
Look into using statements to ensure objects are disposed of.
Use SqlParameterCollection.Add method instead of AddWithValue, it has to infer the data types and this could cause unintended results.
When declaring your parameters, please specify/add the correct data type and length that matches the column data type and length on the table.

Either modify your SQL statement to include the missing column:
INSERT INTO Registration VALUES (#Registration_ID,#Student_ID,#Course_ID,#Section,#Start_Date,#End_Date,#Semester)
or specify the columns that will be populated in your new row (assuming your Registration_ID field is an auto-identifier)
INSERT INTO Registration (Student_ID, Course_ID, Section, Start_Date, End_Date, Semester) VALUES (#Student_ID,#Course_ID,#Section,#Start_Date,#End_Date,#Semester)

you can try this code
using(SqlConnection connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO Table(id,name,test)
VALUES(#param1,#param2,#param3)";
using(SqlCommand cmd = new SqlCommand(sql,connection))
{
cmd.Parameters.Add("#param1", SqlDbType.Int).value = val;
cmd.Parameters.Add("#param2", SqlDbType.Varchar, 50).value = Name;
cmd.Parameters.Add("#param3", SqlDbType.Varchar, 50).value = Test;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}

Related

System.ArgumentException: 'Cannot find column named Party_Name

I get a not found error even though the table exists in the database. How can I solve this problem?
private void button6_Click_1(object sender, EventArgs e)
{
Aconnection.Open();
int selectedRowIndex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedRowIndex];
string parti_Name = Convert.ToString(selectedRow.Cells["Parti_Name"].Value); //Parti = Party(in English)
string oy_Oran = Convert.ToString(selectedRow.Cells["Oy_Oran"].Value); //oy = Vote / Oran = Rate (in English)
OleDbCommand cmd = Aconnection.CreateCommand();
cmd.CommandText = "INSERT INTO OY (Parti_Name, Oy_Oran) VALUES (?, ?, ?)";
cmd.Parameters.AddWithValue("#Parti_Name", parti_Name);
cmd.Parameters.AddWithValue("#Oy_Oran", oy_Oran);
cmd.ExecuteNonQuery();
Aconnection.Close();
}
DataAccess
error
I tried different ways but still got the same error.
As long as you have made a correct connection to your access database, you should be able to execute the parameterized INSERT statement.
You have not mentioned the parameter names in your INSERT sql statement. Change your INSERT statement so as to mention the parameter names instead of just the "?" symbol.
Like this
cmd.CommandText = "INSERT INTO OY (Parti_Name, Oy_Oran)
VALUES (#Parti_Name, #Oy_Oran)";
Also, you are having only 2 column names in the INSERT statement, then no need to pass 3 "?" symbols.

I cannot save data to my SQL database using C#

I am new to C#. I am trying to save the numbers into a SQL Server database table (locally) but I get an error:
Cannot insert the value NULL into column
My code:
private void SaveBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\fn1965\Desktop\Work\TESTDB\NumDB.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
string insert_query = "INSERT into [NumericTable] (Num1, Num2, Total) VALUES (#Num1, #Num2, #Total)";
SqlCommand cmd = new SqlCommand(insert_query, conn);
cmd.Parameters.AddWithValue("#Num1", textBox1.Text);
cmd.Parameters.AddWithValue("#Num2", textBox2.Text);
cmd.Parameters.AddWithValue("#Total", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record saved");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("EROR:"+ ex.ToString());
}
}
Table schema
You can see in the image that the column Id is the only one that does not support null values. Since the column is not identity and as you are not providing a value on your insert, then the INSERT fail with the given exception. This code will work (only if there isn't a record with Id = 1 already):
string insert_query = "INSERT into [NumericTable] (Num1,Num2,Total, Id) Values (#Num1,#Num2,#Total, #id)";
SqlCommand cmd = new SqlCommand(insert_query, conn);
cmd.Parameters.AddWithValue("#Num1", textBox1.Text);
cmd.Parameters.AddWithValue("#Num2", textBox2.Text);
cmd.Parameters.AddWithValue("#Total", textBox3.Text);
cmd.Parameters.AddWithValue("#Id", 1);
cmd.ExecuteNonQuery();
I assume that this is obviously not the desired fuctionality. What you should do is either set the Id column to identity = true or set a value on the insert.
I also encourage you to not use AddWithValue method since it can lead you to some undesired problems. You can read more here: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
That screenshot you took of your table columns design; get back to that, then click the id column, look in the Properties grid for Identity Specification (might need to expand it) and set it to Yes. Set other properties relevant to your needs and save the table.
Borrowed from another SO question:
There are ways to do this from script but they're generally longer/more awkward than using the UI in management studio.
This will (should) change th column so it auto inserts an incrementing number into itself when you insert values for other rows. Someone else has posted an answer as to how to insert values for it yourself but my recommendation to you as a learner is to use auto increment to save the additional needless complication of providing your own primary key values

Add column to sql table with c#

Hello I got a big problem I am trying to add a new column to my MSSQL Database Table and i tried it like thousand times but it wont work.
My destination is to press a button then use the function "eventsspalte_Hinzufügen" to add a new column with the name thats Inserted by the user.
This is the snippet.
private void eventsspalte_Hinzufügen()
{
SQL_eingabe = "ALTER TABLE Teilnahmen_Events ADD #tbName bit NOT NULL ;"; // CONSTRAINT strconst3 DEFAULT 0
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = SQL_eingabe;
cmd.Parameters.AddWithValue("#tbName", tb_Eventname.Text);
cmd.ExecuteNonQuery();
con.Close();
}
The Exception says that cmd.ExecuteQuery() is not able to Execute the sql Command because of the wromg Syntax at #tbName I also tried to use a variable like:
ALTER TABLE Teilnahmen_Events ADD'"+ tb_Eventname.Text +"'bit NOT NULL ;";
but it also didnt work...
I hope you got an solution for me thank you very much.
you cannot pass column name as parameter.
In your second example, single quotes are not needed, so change it into
ALTER TABLE Teilnahmen_Events ADD "+ tb_Eventname.Text +" bit NOT NULL ;";

Error Using SqlCeCommandBuilder while inserting row with column identity turned on

I am trying to use the SqlCeCommandBuilder, and I am having an issue with it. My table, I am using has three columns. The first is set to primary key, and identity is on and set to increment by one. When I am creating my SqlCeCommand, I cannot get it to execute. I thought if I leave that column out, it will automatically add the value, but it returns an error stating the number of columns in the command have to match the number of columns in the table. So if I add the "BillerID" column to the command builder, it says I need to add a value for it. Then when I add a value, it says that the column "BillerID" cannot be modified. What am I doing wrong?
using (SqlCeConnection con = new SqlCeConnection(Properties.Settings.Default.BillsConnectionStringDefault))
{
con.Open();
try
{
using (SqlCeCommand command = new SqlCeCommand(
"INSERT INTO Billers VALUES(#BillerID, #Name, #Type)", con))
{
command.Parameters.Add(new SqlCeParameter("BillerID", 999999));
command.Parameters.Add(new SqlCeParameter("Name", billerName));
command.Parameters.Add(new SqlCeParameter("Type", "0"));
command.ExecuteNonQuery();
}
}
catch(Exception ex)
{
MessageBox.Show(string.Format(ex.Message.ToString()));
}
}
You can specify the columns you're inserting into, try changing the query to this:
"INSERT INTO Billers (Name, Type) VALUES(#Name, #Type)"
and leaving out the ID parameter entirely.

Unable to insert data into SQL Database using C#

I'm writing a method to insert a Student into a local SQL database that contains a table with information about Students:
public void AddStudent(string name, string teachName, string pass)
{
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\Logo.sdf";
SqlCeConnection connection = new SqlCeConnection("Data Source=" + dbfile + "; Password = 'dbpass2011!'");
connection.Open();
SqlCeTransaction transaction = connection.BeginTransaction();
SqlCeCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "INSERT INTO Students VALUES ('#name', '#id', '#pass', '#tname')";
command.Parameters.Add("#name", name);
command.Parameters.Add("#id", this.ID);
command.Parameters.Add("#pass", MD5Encrypt.MD5(pass));
command.Parameters.Add("#tname", teachName);
command.Prepare();
command.ExecuteNonQuery();
transaction.Commit();
connection.Dispose();
connection.Close();
}
Whenever I use this, it never inserts the data to the table when I look at the contents of the Students table in the database. Originally I had this return an int so I could see how many rows it affected, which it always returned 1, so I know it's working.
I've looked for answers to this, and the answer to similar questions was that the person asking was looking at the wrong .sdf file. I've made sure that I'm looking at the right file.
Any feedback would be much appreciated!
command.CommandText = "INSERT INTO Students VALUES ('#name', '#id', '#pass', '#tname')";
You should remove the extra single quotes - this should be:
command.CommandText = "INSERT INTO Students VALUES (#name, #id, #pass, #tname)";
Also I am not sure why you open a transaction for a single insert - that is also not needed.
You don't need to put single quote to parametrized query, in case of parametrized query the whole data will be parsed as required,
command.CommandText = "INSERT INTO Students VALUES (#name, #id, #pass, #tname)";
Also, its better to set parameter type, size and value explicitly as below:
SqlCeParameter param = new SqlCeParameter("#name", SqlDbType.NVarChar, 100);
param.Value = name; // name is a variable that contain the data of name field
//param.Value = 'Jhon Smith'; //Directly value also can be used
Hope this would be helpful, thanks for your time.
There is most likely an exception being raised in your code; you need to add a try/catch handler and/or debug the application to figure out exactly what is happening.
However, there are at least two issues with your code:
The prepare statement requires the data types of the parameters. From the MSDN documentation:
Before you call Prepare, specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable-length data type, you must set the Size property to the maximum size needed. Prepare returns an error if these conditions are not met.
You need to close the connection before disposing it (this won't affect the insert, however).

Categories

Resources