This code when used in MS-Access is running and updating in property, but when using through database it's giving syntax error
string item = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string h="update Follow_Date set Current_Date='" + dateTimePicker1.Value.ToLongDateString() + "', Current_Time='" + dateTimePicker3.Value.ToLongTimeString() + "', Type='" +
comboBox1.SelectedItem.ToString() + "', Remarks='" +
textBox1.Text + "', Next_Follow_Date='" + dateTimePicker2.Value.ToLongDateString()+ "' where Follow_Id='" +
item.ToString() +"'";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\lernovo\Documents\JDB.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand(h, con);
cmd.ExecuteNonQuery();
Error is syntax error.
string item = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string h="update Follow_Date set #Current_Date, #Current_Time, #Type, #Remarks, #Next_Follow_Date where #Follow_Id";
try
{
Using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\lernovo\Documents\JDB.mdb"))
{
con.Open();
Using (OleDbCommand cmd = new OleDbCommand(h, con))
{
cmd.Parameters.Add("Current_Date", dateTimePicker1.Value.ToLongDateString());
cmd.Parameters.Add("Current_Time", dateTimePicker3.Value.ToLongTimeString());
cmd.Parameters.Add("Remarks", textBox1.Text);
cmd.Parameters.Add("Type", comboBox1.SelectedItem.ToString());
cmd.Parameters.Add("Next_Follow_Date", dateTimePicker2.Value.ToLongDateString());
cmd.Parameters.Add("Follow_Id", item.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch(SQLException ex)
{
System.Console.WriteLine(ex.Message, ex.StackaTrace)
}
You're not closing your Database connection and try to use Parameter instead of concatenation(Probe to SQL Injection).
Catch your error message and it trace it using StackTrace. Try to use Using statement to dispose object properly.
Looks like a trivial mistake...
You must have to open the db connection before executing queries on it..
conn=new conn(db param);
try
{
conn.open()
}
catch(Exception e)
{
e.getMessage();
}
Related
I know plenty of people have these issues, and I've actually tried to implement some of the suggestions to my code, however I'm getting errors that just don't make sense to me. This is my first time implementing database calls to my code. Can someone please tell me what I'm doing wrong? The following error pops up: ERROR: Invalid object name 'Main'. This is actually triggered by my exception so at least something is working. Otherwise, I don't know what the issue is. On the DB end, I have (username VARCHAR, email VARCHAR and number NCHAR) Please see the code below
static string path = Path.GetFullPath(Environment.CurrentDirectory);
static string databaseName = "u_DB.mdf";
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName + "; Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
// string query = "INSERT INTO UserInfo '" + textBox1.Text + "' and password = '" + textBox2.Text + "'";
string query = "insert into Main ([username], [email], [number]) values(#username,#email,#number)";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.AddWithValue("#number", SqlDbType.VarChar).Value = textBox1.Text;
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
MessageBox.Show("Added to Database");
else
MessageBox.Show("Nothing was added");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
con.Close();
}
}
Firstly, as Chetan assumed, do you have a main table?
The syntax of the query you are using is :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Furthermore,
AddWithValue(string parameterName, object value (<== The actual value to insert!));
in your case
AddWithValue("#number", textBox1.Text);
is enough.
i have a button that when clicked inserts data from textbox and combobox fields into database tables, but every time i insert it gives me "Invalid attempt to call read when reader is closed". How can i get rid of this error. And tips on optimising the code are welcome, because i know im a total noob. thanks
private void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query1 = "insert into location(Storage, Shelf, columns, rows) values(" + txtWarehouse.Text + ", " + txtShelf.Text + ", " + txtColumn.Text + ", " + txtRow.Text + ")";
SqlCommand sqlCmd = new SqlCommand(Query1, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query3 = "SELECT LOCATION_ID FROM LOCATION WHERE storage='" + txtWarehouse.Text + "' AND shelf='" + txtShelf.Text + "' AND columns='"
+ txtColumn.Text + "' AND rows='" + txtRow.Text + "'";
SqlCommand sqlCmd1 = new SqlCommand(Query3, sqlCon);
SqlDataReader dr = sqlCmd1.ExecuteReader(); ;
while (dr.Read())
{
string LocationId = dr[0].ToString();
dr.Close();
string Query2 = "insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID) values ('" + txtSku.Text + "','" + txtNimetus.Text + "', '"
+ txtMin.Text + "', '" + txtMax.Text + "', '" + txtQuan.Text + "', '" + LocationId + "', '" + (cbCat.SelectedIndex+1) + "', '" + (cbMail.SelectedIndex+1) + "')";
SqlCommand sqlCmd = new SqlCommand(Query2, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
}
sqlCon.Close();
}
catch (Exception ed)
{
MessageBox.Show(ed.Message);
}
}
Let's try to make some adjustments to your code.
First thing to consider is to use a parameterized query and not a
string concatenation when you build an sql command. This is mandatory
to avoid parsing errors and Sql Injections
Second, you should encapsulate the disposable objects in a using statement
to be sure they receive the proper disposal when you have finished to
use them.
Third, you can get the LOCATION_ID from your table without running a
separate query simply adding SELECT SCOPE_IDENTITY() as second batch to your first command. (This works only if you have declared the LOCATION_ID field in the first table as an IDENTITY column)
Fourth, you put everything in a transaction to avoid problems in case
some of the code fails unexpectedly
So:
SqlTransaction tr = null;
try
{
string cmdText = #"insert into location(Storage, Shelf, columns, rows)
values(#storage,#shelf,#columns,#rows);
select scope_identity()";
using(SqlConnection sqlCon = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, sqlCon))
{
sqlCon.Open();
using( tr = sqlCon.BeginTransaction())
{
// Prepare all the parameters required by the command
cmd.Parameters.Add("#storage", SqlDbType.Int).Value = Convert.ToInt32(txtWarehouse.Text);
cmd.Parameters.Add("#shelf", SqlDbType.Int).Value = Convert.ToInt32(txtShelf.Text);
cmd.Parameters.Add("#columns", SqlDbType.Int).Value = Convert.ToInt32(txtColumn.Text );
cmd.Parameters.Add("#rows", SqlDbType.Int).Value = Convert.ToInt32(txtRow.Text);
// Execute the command and get back the result of SCOPE_IDENTITY
int newLocation = Convert.ToInt32(cmd.ExecuteScalar());
// Set the second command text
cmdText = #"insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID)
values (#sku, #nimetus,#min,#max,#qty,#locid,#catid,#ordid)";
// Build a new command with the second text
using(SqlCommand cmd1 = new SqlCommand(cmdText, sqlCon))
{
// Inform the new command we are inside a transaction
cmd1.Transaction = tr;
// Add all the required parameters for the second command
cmd1.Parameters.Add("#sku", SqlDbType.NVarChar).Value = txtSku.Text;
cmd1.Parameters.Add("#nimetus",SqlDbType.NVarChar).Value = txtNimetus.Text;
cmd1.Parameters.Add("#locid", SqlDbType.Int).Value = newLocation;
.... and so on for the other parameters required
cmd1.ExecuteNonQuery();
// If we reach this point the everything is allright and
// we can commit the two inserts together
tr.Commit();
}
}
}
}
catch (Exception er)
{
// In case of exceptions do not insert anything...
if(tr != null)
tr.Rollback();
MessageBox.Show(er.Message);
}
Notice that in the first command I use parameters of type SqlDbType.Int because you haven't used single quotes around your text. This should be verified against the real data type of your table columns and adjusted to match the type. This is true as well for the second command where you put everything as text albeit some of those fields seems to be integer (_location_id_ is probably an integer). Please verify against your table.
The code doesn't produce an exception and seemingly runs fine. But after running it and checking the table i see that the row is not inserted. I use navicat for cheking and that's not the problem. I've double-checked the table name and field names which all correct. What's wrong?
try
{
SQLiteConnection conn = new SQLiteConnection("Data Source=path;Version=3;FailIfMissing=True");
conn.Open();
String sql = "INSERT INTO sales (cust_id, date, cost, price) VALUES ('0', '" + String.Format("{0:u}", DateTime.Now.Date).Split(' ')[0] + "', '" + cost.ToString() + "', '12')";
SQLiteCommand command = new SQLiteCommand(sql, conn);
conn.Close();
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
add:
command.ExecuteNonQuery();
on your code:
...
SQLiteCommand command = new SQLiteCommand(sql, conn);
command.ExecuteNonQuery();
Also it is always better to use parameters on your query
I've tried this code:
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =" + textBox1.Text;
OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb");
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.ExecuteNonQuery();
Error: Data type mismatch in criteria expression, at the line:
My_Command.ExecuteNonQuery();
Use parametrized query to avoid all kind of errors
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =?";
using(OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb"))
{
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.Parameters.Add("#p1", textBox1.Text);
My_Command.ExecuteNonQuery();
}
In your case the Room NUmber field is of Text type so, you need to enclose the value in single quotes, but this is really wrong. You expose your code to maliciuos text written by your user inside the text box. A very simple and funny example here
Which type is your [Room Number] column? If it is a string then you have to write the value with inverted comma or quotation mark (I'm not sure which of both is used in Access).
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] = '" + textBox1.Text + "'";
To avoid SQL injektion you should use Parameters instead of the string operation.
public static void DeleteLine(string kv)
{
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
try
{
OleDbConnection con = new OleDbConnection("provider = microsoft.ace.oledb.12.0;data source = E:\\Sohkidatabase\\Sohki.accdb");
con.Open();
str = "select * from compny_info where id=" + comboBox1.Text.Trim() + "";
com = new OleDbCommand(str, con);
OleDbDataReader reader = com.ExecuteReader();
if (reader.Read())
{
textBox1.Text = reader["regis_no"].ToString();
textBox2.Text = reader["comp_oner"].ToString();
textBox3.Text = reader["comp_name"].ToString();
textBox4.Text = reader["comp_add"].ToString();
textBox5.Text = reader["tin_no"].ToString();
textBox6.Text = reader["email"].ToString();
}
con.Close();
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
public static void DeleteLine(string kv) {
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'" ;
}
i have a webservice and a comsumer, the webservice has its methode where it returns data from a mysql database.
in the comsumer i called
WebService.Service1 Service = new WebService.Service1();
in the beginning (not within a methode)
when the consumer starts asking for data it will be 20 requests within 10 minutes first 15-18 requests worked perfectly but the last few times it returns the error
Server was unable to process request. ---> The connection is already
open.
I hope i provided enough information like this, i rather not post the code.
This is the methode of the webservice:
public string GetAnswer(string Question, string Option1, string Option2, string Option3, string Option4)
{
string connstring = "Server=Server;Port=3306;Database=DB;UID=User;password=pw;";
MySqlConnection conn = new MySqlConnection(connstring);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM `tbl` where `Question` = '" + Question + "' LIMIT 1";
conn.Open();
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string TheAnswer = "";
while (reader.Read())
{
string question = reader["Question"].ToString();
string answer = reader["Answer"].ToString();
if (Option1.Equals(answer))
TheAnswer = Option1;
if (Option2.Equals(answer))
TheAnswer = Option2;
if (Option3.Equals(answer))
TheAnswer = Option3;
if (Option4.Equals(answer))
TheAnswer = Option4;
}
conn.Close();
conn.Dispose();
return TheAnswer;
}
else
{
MySqlCommand command2 = conn.CreateCommand();
command.CommandText = "Insert Into `new` (`Question`, `Answer1`,`Answer2`,`Answer3`,`Answer4`) VALUES ('" + Question + "','" + Option1 + "','" + Option2 + "','" + Option3 + "', '" + Option4.Replace("~", " ") + "')";
conn.Open();
command.ExecuteNonQuery();
conn.Close();
conn.Dispose();
return "Error: Question is unknown, saving the question to get it answered.";
}
}
You have conn.open() in your else statement, and the connection was already opened before that. You should probably consider using the using statement:
using (MySqlConnection conn = new MySqlConnection(connstring))
{
using (MySqlCommand command2 = conn.CreateCommand())
{
}
}