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.
Related
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();
}
}
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 ;";
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO tbl_AStatus (Asset Status,Remarks) VALUES (#a, #b)", Login.sqlConn);
cmd.Parameters.AddWithValue("#a", txtAssetStatus.Text);
cmd.Parameters.AddWithValue("#b", txtRemarks.Text);
int a = cmd.ExecuteNonQuery();
MessageBox.Show(a.ToString());
Exception shown:
There was an error parsing the query. [ Token line number = 1,Token
line offset = 32,Token in error = Status ]
If your table name or column names includes white space, you need to use them with square brackets like [Asset Status]. But this is not recommended. Would be better changing your column name to something else if you can.
Read: Database, Table and Column Naming Conventions?
Also use using statement to dispose your database connections and objects.
using(SqlCeCommand cmd = Login.sqlConn.CreateCommand())
{
cmd.CommandText = "INSERT INTO tbl_AStatus ([Asset Status],Remarks) VALUES (#a, #b)";
cmd.Parameters.Add("#a", SqlDbType.NVarChar).Value = txtAssetStatus.Text;
cmd.Parameters.Add("#b", SqlDbType.NVarChar).Value = txtRemarks.Text;
// I assume your column types are NVarChar
Login.sqlConn.Open();
int a = cmd.ExecuteNonQuery();
MessageBox.Show(a.ToString());
}
And don't use AddWithValue method. It may generate unexpected results sometimes. Use SqlParameterCollection.Add method and it's overloads.
Read: Can we stop using AddWithValue() already?
I have a form with first name , last name , email, supervisor. I then have my code behind on button set to this
private void agentInsertButton_Click(object sender, EventArgs e)
{
try
{
ad.InsertCommand = new OleDbCommand("insert into Agents values ([FirstName],[LastName],[Email],[Supervisor])", con);
ad.InsertCommand.Parameters.Add("#FirstName", OleDbType.VarChar).Value = agentNametextBox1.Text.ToString();
ad.InsertCommand.Parameters.Add("#LastName", OleDbType.VarChar).Value = agentLastNametextBox4.Text.ToString();
ad.InsertCommand.Parameters.Add("#Email", OleDbType.VarChar).Value = agentEmailtextBox3.Text.ToString();
ad.InsertCommand.Parameters.Add("#Supervisor", OleDbType.VarChar).Value = agentSupervisortextBox2.Text.ToString();
con.Open();
ad.InsertCommand.ExecuteNonQuery();
con.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
};
I am getting error number of query values and destination fields are not the same . I am sure it is how I have the DB sending over the variables and the AgentID causing the issue. I am new to access but that is what my work is wanting to use. Look forward to a solid answer.
I am just using a simple access database named Agents
Fields are
AgentID - auto number
FirstName - text
LastName - text
Email - text
Supervisor - text
When you write an INSERT statement it must either be like this:
INSERT INTO TableName VALUES (ValueList)
in which case you must provide values for every column and in the order that they were added to the table, or like this:
INSERT INTO TableName (ColumnList) VALUES (ValueList)
in which case you can specify a subset of the columns and in any order. You have done neither. You have done this:
INSERT INTO TableName VALUES (ColumnList)
which is meaningless. Your SQL needs to be like this:
insert into Agents ([FirstName],[LastName],[Email],[Supervisor]) values (#FirstName,#LastName,#Email,#Supervisor)
Note that the values now match the parameters that you add to the command.
Change your query like this
ad.InsertCommand = new OleDbCommand("insert into Agents values (#FirstName,#LastName,#Email,#Supervisor)", con);
or
ad.InsertCommand = new OleDbCommand("insert into Agents (FirstName,LastName,Email,Supervisor) values (#FirstName,#LastName,#Email,#Supervisor)", con);
OleDb is index-based and doesn't use named parameters.
Change as follows:
ad.InsertCommand = new OleDbCommand("insert into Agents (FirstName, LastName, Email, Supervisor) values (?, ?, ?, ?)", con);
ad.InsertCommand.Parameters.AddWithValue("?", agentNametextBox1.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentLastNametextBox4.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentEmailtextBox3.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentSupervisortextBox2.Text);
private void btnID_Click(object sender, EventArgs e)
{
//Set Up Conncetion
SqlConnection myconnection = new SqlConnection(global::Database_connection_inForm.Properties.Settings.Default.Database1ConnectionString);
try
{
string sql = "INSERT INTO Students(Student ID,Student Name) values("+txtID.Text+",'"+txtName.Text+"')";
//Command object
SqlCommand exeSql = new SqlCommand(sql, myconnection);
myconnection.Open(); //Opening connection
exeSql.ExecuteNonQuery();
MessageBox.Show("Add new Record Done!","Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
this.studentsTableAdapter.Fill(this.database1DataSet.Students);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
myconnection.Close();
}
}
private void btnRef_Click(object sender, EventArgs e)
{
this.studentsTableAdapter.Fill(this.database1DataSet.Students);
}
}
When a column name contains spaces you should always encapsulate that name with square brackets
sql = "INSERT INTO Students([Student ID],[Student Name]) ....."
Said that, please remove your string concatenation and use a parameterized query ALWAYS.
It is far better to use parameters instead of string concat. The main reason is to avoid Sql Injection but the parameter approach will also remove the quoting problem (IE a name = 'O'Brian' leads to a syntax error when using string concat)
private void btnID_Click(object sender, EventArgs e)
{
try
{
string sql = "INSERT INTO Students([Student ID],[Student Name]) " +
"values (#id, #name)";
using(SqlConnection myconnection = new SqlConnection(....))
using(SqlCommand exeSql = new SqlCommand(sql, myconnection))
{
myconnection.Open();
exeSql.Parameters.AddWithValue("#id",Convert.ToInt32(txtID.Text));
exeSql.Parameters.AddWithValue("#name",txtName.Text);
exeSql.ExecuteNonQuery();
}
}
.....
Also notice that I have converted the txtID.Text contents to an integer without any checking.
This could fail if your user types something that is not a valid numeric id (And if the Student ID is an Identity column then this value should never be passed in the INSERT statement)
As a final note. Do you really need these columns names? It is far better to have them without spaces otherwise you will get this problem every time you use this table
If your identifiers contain spaces, you have to delimit the identifier. The way you do that depends on the database you are using.
In SQL Server you use Square brackets:
string sql = "INSERT INTO Students([Student ID],[Student Name]) values(#Id,#Name)";
In MySQL you use backticks:
string sql = "INSERT INTO Students(`Student ID`,`Student Name`) values(#Id,#Name)";
Note that I have replaced the concatenated values in the queries with parameters. You should use parameterised queries, otherwise your code is wide open to SQL injection attacks.
First of all you did not Use Correct naming convention
you should use
StudentId Or Student_Id ( the first one is recommended)
when you have space between you column Names you should use "[" "]" and cover your column name
You have a space in column name
string sql = "INSERT INTO Students(Student ID,Student Name) values("+txtID.Text+",'"+txtName.Text+"')";
thats a problem - check a column name and use a right column name.