I'm writing a script to add a bug report in the bug tracking system.
While after clicking the submit button, the SQL syntax error dialog have been pop-up.
Here is my coding
public partial class AddBugForm : Form
{
public AddBugForm()
{
InitializeComponent();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
void Fillcombo()
{
string constring = "datasource = localhost; username = root; password = ";
string Query = "select * from bug.type";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string type = myReader.GetString("Type_of_bug");
comboBox1.Items.Add(type);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Fillcombo1()
{
string constring1 = "datasource = localhost; username = root; password = ";
string Query1 = "select * from bug.severity";
MySqlConnection conDataBase1 = new MySqlConnection(constring1);
MySqlCommand cmdDataBase1 = new MySqlCommand(Query1, conDataBase1);
MySqlDataReader myReader;
try
{
conDataBase1.Open();
myReader = cmdDataBase1.ExecuteReader();
while (myReader.Read())
{
string severity = myReader.GetString("severity");
severity_combo.Items.Add(severity);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Fillcombo2()
{
string constring2 = "datasource = localhost; username = root; password = ";
string Query2 = "select * from bug.priority";
MySqlConnection conDataBase2 = new MySqlConnection(constring2);
MySqlCommand cmdDataBase2 = new MySqlCommand(Query2, conDataBase2);
MySqlDataReader myReader;
try
{
conDataBase2.Open();
myReader = cmdDataBase2.ExecuteReader();
while (myReader.Read())
{
string priority = myReader.GetString("priority");
priority_combo.Items.Add(priority);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void submit_button_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;username=root;password=";
string Query = "INSERT INTO 'bug.bug' (Bug_ID, title, Type_of_bug, software, software_version, description, step_to_reproduction, severity, priority, symptom) values('" + this.bugid_txt.Text+"', '" + this.title_txt.Text + "','" + this.comboBox1.Text + "','" + this.software_txt.Text + "','" + this.software_version_txt.Text + "','" + this.description_txt.Text + "','" + this.step_to_reproduction_txt.Text + "','" + this.severity_combo.Text + "','" + this.priority_combo.Text + "','" + this.symptom_txt.Text + "');";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Saved");
while(myReader.Read())
{
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Please help me :((((
I see two issues with context of syntax error in your INSERT query
first, INSERT INTO 'bug.bug'; remove those single quotes else it's a literal value and not table name. It should be INSERT INTO bug.bug
Second, remove the semicolon from last of your query statement
.... + this.symptom_txt.Text + "');";
^.... this semicolon
replace this INSERT INTO 'bug.bug' by
INSERT INTO `bug.bug`
your table name is tarted as string and mysql engine doesn't see the table.
What is the syntax error you are getting?
Couple of points regarding the Insert statement.
You should not build the SQL command string by combining the value strings, this can create SQL injection problems and easily cause syntax errors. Instead you should use Parameters. Parameters also make the syntax a lot simpler.
You should use the ExecuteNonQuery command instead of a Reader, as the Insert statement is not reading any data
Updated statement (only two values used to make it smaller):
string Query = "INSERT INTO bug.bug (Bug_ID, title) values (#id, #title)"
MySqlConnection conDataBase = new MySqlConnection (constring);
MySqlCommand cmdDataBase = new MySqlCommand (Query, conDataBase);
cmdDataBase.Parameters.AddWithValue ("#id", bugid_txt.Text)
cmdDataBase.Parameters.AddWithValue ("#title", title_txt.Text)
conDataBase.Open();
cmdDataBase.ExecuteNonQuerty ();
MessageBox.Show("Saved");
Using Parameters will probably solve your syntax error.
Related
I am trying to retrieve data from a Database and show them on a form; but my code isn't working... I've got no errors, and logically it seems to work (to me) so I cannot figure out where I have gone wrong. That's where I need your help!
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
The 'tableListBox' is populated with all the values in column 'Default_Name'. I want it so that when the 'Default_Name' is selected from the list box it shows the values, in textboxes and comboboxes, that correspond with that row in the Database.
Any and all help would be appreciated. Thanks.
I'm going to start by changing your design a bit and suggest that perhaps you look at using a datatable and then just retrieving the rows from the datatable.
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
private DataTable dataTable;
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
foreach(DataRow row in dataTable.Rows)
{
textBox1.Text = row[2].ToString();
comboBox1.Text = row[3].ToString();
comboBox3.Text = row[4].ToString();
textBox2.Text = row[6].ToString();
comboBox2.Text = row[7].ToString();
comboBox4.Text = row[8].ToString();
}
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I generally find that DataTables are more reliable than looping through the actual reader. Ofcourse this assumes that there is data being returned. Also try changing your select statement to this
string Query = "SELECT * FROM [Table]"
If that works, then the problem could be
There is no default name of the specified value or
tableListBox.SelectedValue is not returning any value, in which case, have a look at your listbox selected value
Thanks to Takarii for helping. I figured out who to make it work.
private void tableListBox_SelectedValueChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE ID = '" + tableListBox.SelectedIndex.ToString() + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
First I changed the void to 'SelectedValueChanged' and then I changed the 'WHERE' in the connection Query to the Row Index associated with the selected Value.
Thanks for everyone's help!
i have this code for insert data into access 2013
after click in the save button data insert into dataGridView and show
and when stop program and restart this,data not stored in the DB.I've done a lot of searches but can't find the solution. my class code and my button save code
class DB
{
public static OleDbConnection con = new OleDbConnection();
static DB()
{
con.ConnectionString = "Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|//Phonebook-db.accdb;Persist Security Info=True";
}
public static void Insert(Person p1)
{
try
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES('" + p1.Name + "','" + p1.Family + "','" + p1.Telephone + "','" + p1.Major + "')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = s;
cmd.ExecuteNonQuery();
con.Close();
System.Windows.Forms.MessageBox.Show("Record successfully Added");
}
catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
}
}
Person p = new Person();
p.Name = txtname.Text;
p.Family = txtfamily.Text;
p.Telephone = txttell.Text;
p.Major = txtmajor.Text;
DB.Insert(p);
txttell.Text = "";
txtmajor.Text = "";
txtname.Text = "";
txtfamily.Text = "";
List<Person> people = DB.GetPeople();
dataGridView1.DataSource = people;
Choose your ACCDB file listed in your project files, select Copy To Output Directory and set its value to Never (And remember that |DataDirectory| is a substitution strings that points (for ASP.NET projects) to APP_DATA, your record is inserted in the database copied in that directory.
Said that please consider to use a parameterized query to create an sql command, not string concatenations
try
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES(" +
"?,?,?,?)";
cmd.CommandText = s;
cmd.Parameters.AddWithValue("#p1",p.Name);
cmd.Parameters.AddWithValue("#p2",p.Family);
cmd.Parameters.AddWithValue("#p3",p.Telephone);
cmd.Parameters.AddWithValue("#p4",p.Major);
cmd.ExecuteNonQuery();
con.Close();
System.Windows.Forms.MessageBox.Show("Record successfully Added");
}
catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
Of course do not close the connection before executing the command.
Another point to change is the usage pattern of your connection. Do not create a global connection and keep it around for the lifetime of your application. Simply create and use it when needed and close/dispose immediately after
using(OleDbConnection con = new OleDbConnection("Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|//Phonebook-db.accdb;" +
"Persist Security Info=True"))
{
try
{
OleDbCommand cmd = con.CreateCommand();
....
}
} // <- Here at the closing brace the connectio will be close and disposed
How do I pass a stored procedure along with parameters as a string to a function?
I tried this code but no luck..
This is the Business Access Layer code
try
{
string Query_string = "SP_InsertOffer_Tab #offer_name ='" + this.offer_name +"', #offer_price = " + this.offer_price + ",#start_date = '" + this.start_date +
"',#end_date = '" + this.end_date + "'";
int result = DbAcess.Insert_Query(Query_string);
return result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
DbAcess = null;
}
Database layer code is as follows
public int Insert_Query(string strSQL)
{
SqlConnection con = new SqlConnection();
con = OpenConnection();
try
{
sqlcmd = new SqlCommand();
sqlcmd.Connection = con;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = strSQL;
int Result = sqlcmd.ExecuteNonQuery();
return Result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
Instead of passing strSQL as the CommandText, where strSQL is the string you create in the first code block (I think...), just pass the SP name as the CommandText and then add Parameters to your sqlcmd object.
SqlParameter p = new SqlParameter("#ParameterName", parametervalue));
sqlcmd.Parameters.Add(p);
Just to try to RESOLVE your problem, but BEWARE that this method is very dangerous and NOT RECOMMENDED for the Sql Injection problem.
string Query_string = "EXEC SP_InsertOffer_Tab #offer_name ='" +
this.offer_name +"', #offer_price = " +
this.offer_price + ",#start_date = '" +
this.start_date + "',#end_date = '" + this.end_date + "'";
and change the CommandType to Text.
A better approach would be to change the Insert_Query method
public int Insert_Query(string strSQL, SqlParameter[] prm)
{
using(SqlConnection con = OpenConnection())
{
sqlcmd = new SqlCommand(strSql, con);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddRange(prm)
int Result = sqlcmd.ExecuteNonQuery();
return Result;
}
}
then call it in this way
SqlParameter[] prms = new SqlParameter[]
{
new SqlParameter("#offer_name", SqlDbType.NVarChar),
new SqlParameter("#offer_price", SqlDbType.Money),
new SqlParameter("#start_date", SqlDbType.SmallDateTime),
new SqlParameter("#end_date", SqlDbType.SmallDateTime)
};
prms[0].Value = this.offer_name;
prms[1].Value = this.offer_price;
prms[2].Value = this.start_date;
prms[3].Value = this.end_date;
int result = DbAcess.Insert_Query(Query_string, prms);
When the event Button is pressed nothing updates in the SQL Table and no errors display.
protected void SubmitBTN_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Matt\Documents\coffeeShop.mdf;Integrated Security=True;Connect Timeout=30");
String coffeeName = NameTXT.Text;
String coffeeGrid = GrindTXT.Text;
String coffeeOrigin = OriginTXT.Text;
String coffeePrice = PriceTXT.Text;
String coffeeQty = QuantityTXT.Text;
String coffeeRRP = RRPTXT.Text;
SqlCommand comm = new SqlCommand("INSERT INTO Table (coffeeName, coffeeGrid, coffeeOrigin, coffeePrice, coffeeQty, coffeeRRP) VALUES ('%" + coffeeName + "%','%" + coffeeGrid + "%','%" + coffeeOrigin + "%','%" + coffeePrice + "%','%" + coffeeGrid + "%','%" + coffeeQty + "%','%" + coffeeRRP + "%' ", conn);
conn.Open();
//SqlDataReader reader = comm.ExecuteReader();
//lblDBData.Text += "<table border=0>";
//while (reader.Read())
//{
// lblDBData.Text += "<tr>";
// lblDBData.Text += "<td>" + reader["coffeeName"] + "</td>";
// lblDBData.Text += "</tr>";
//}
//lblDBData.Text += "</table>";
//reader.Close();
conn.Close();
}
Any advice would be much appreciated, Many thanks
Add:
comm.ExecuteNonQuery();
After:
conn.Open();
By the way, you would want to use parameters instead of " + parameter + " on query to avoid sql injection. Read this:
http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06
You need to execute the command as;
conn.Open(); //Open the connection to the database
comm.ExecuteNonQuery(); //This line does the insert
conn.Close(); //Close the connection once your command executed.
Also think about parameterised queries and to open connection object within a using block as a good practice to avoid leaving connection objects open.
Ex;
using(SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = new SqlCommand("your query string with #para", conn);
cmd.Parameters.AddWithValue("#para", "value");
conn.Open();
cmd.ExecuteNonQuery();
}
When you executes a Transact-SQL statement, the correct way is:
private const string connection = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Matt\Documents\coffeeShop.mdf;Integrated Security=True;Connect Timeout=30";
protected void SubmitBTN_Click(object sender, EventArgs e)
{
string query = "INSERT INTO Table (coffeeName, coffeeGrid, coffeeOrigin, coffeePrice, coffeeQty, coffeeRRP) VALUES (#name, #grid, #origin, #price, #qty, #rrp)";
using(SqlConnection conn = new SqlConnection(connection))
using(SqlCommand command = new SqlCommand(query, connection))
{
String coffeeName = NameTXT.Text;
String coffeeGrid = GrindTXT.Text;
String coffeeOrigin = OriginTXT.Text;
String coffeePrice = PriceTXT.Text;
String coffeeQty = QuantityTXT.Text;
String coffeeRRP = RRPTXT.Text;
command.Parameters.AddWithValue("#name", coffeeName);
command.Parameters.AddWithValue("#grid", coffeeGrid);
command.Parameters.AddWithValue("#origin", coffeeOrigin);
command.Parameters.AddWithValue("#price", coffeePrice);
command.Parameters.AddWithValue("#qty", coffeeQty);
command.Parameters.AddWithValue("#rrp", coffeeRRP);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (SqlException Ex)
{
console.WriteLine( "Error message: " + Ex);
}
finally
{
command.Connection.Close();
}
}
}
You can't read an insert statement. You have to use comm.executeNonQuery() to execute the insert command, then make a new select statement to read the data
You need to execute the SQL command. Before closing the connection, add this:
comm.ExecuteNonQuery();
For an example, see MSDN:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
I need to perform an update in a table(Homework). But it is not just replacing an old value with a new one; to the already existing value in the column i have to add(SUM) the new value(the column is of type int).
This is what i did so far but i am stuck:
protected void subscribeButton_Click(object sender, EventArgs e)
{
string txtStudent = (selectedStudentLabel.Text.Split(' '))[0];
int studentIndex = 0;
studentIndex = Convert.ToInt32(txtStudent.Trim());
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Trusted_Connection=True;User Instance=yes");
conn.Open();
string sql2 = "UPDATE student SET moneyspent = " + ?????? + " WHERE id=" + studentIndex + ";";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
try
{
conn.Open();
myCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}
}
What should i add intead of ??? to achieve my goal?
Is it possible to do it this way? I want to avoid using to many queries.
If i understand you correctly (i'm not sure i do) you want something like this:
string sql2 = "UPDATE student SET moneyspent = moneyspent + #spent WHERE id=#id";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
myCommand2.Parameters.AddWithValue("#spent", 50 )
myCommand2.Parameters.AddWithValue("#id", 1 )
Notice how i've used parameters and not string concatenation, very important!!