error for insert and stored data in access 2013 - c#

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

Related

Run SQL script from ASP.Net C# application performance issue

I'm running SQL script from C# code, my problem that the code take a long time to finish execution, it has many tables to be created in script(at least 30 Tables), so my code is working but it has performance issue.
this is the code
public static bool executeSqlScript(string scriptPath,string serverName,string databaseName)
{
try
{
SqlConnection myConn = new SqlConnection("Server=.;Integrated security=SSPI;database=master");
Server server = new Server(new ServerConnection(myConn));
string CreateCommand = "CREATE DATABASE " + databaseName + "";
string appendText;
//delete first line from script(Oldscript)
var lines = File.ReadAllLines(scriptPath).Skip(1);
File.WriteAllLines(scriptPath, lines);
using (StreamReader sreader = new StreamReader(scriptPath))
{
appendText = sreader.ReadToEnd();
}
File.Delete(scriptPath);
using (StreamWriter swriter = new StreamWriter(scriptPath, false))
{
appendText = "USE [" + databaseName + "]" + Environment.NewLine + appendText;
swriter.Write(appendText);
swriter.Close();
}
string readtext = File.ReadAllText(scriptPath);
SqlCommand myCommand = new SqlCommand(CreateCommand, myConn);
myConn.Open();
myCommand.ExecuteNonQuery();
server.ConnectionContext.ExecuteNonQuery(readtext);
return true;
}
catch (Exception e)
{
throw e;
return false;
}
}
My recommendation would be to migrate most of this to the SQL Server, once the new DB and User are setup, call a Stored Procedure to read the SQL file with the necessary DDL in it.
My last project was for a managed hosting company, and our CMS utilized well over 150 database objects. We used a "control" database which we pass in the new DB information and it would ceate the new tables, functions, and procedures generally in less than a minute.
use Parallel.ForEach to create tables likes
public static bool executeSqlScript(string scriptPath, string serverName, string databaseName)
{
try
{
SqlConnection myConn = new SqlConnection("Server=.;Integrated security=SSPI;database=master");
//Server server = new Server(new ServerConnection(myConn));
string CreateCommand = "CREATE DATABASE " + databaseName + "";
string appendText;
//delete first line from script(Oldscript)
//create db first
var myCommand = new SqlCommand(CreateCommand, myConn);
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
List<string[]> list = File.ReadLines(scriptPath)
.Select(line => line.ToLower().Split(new string[] { "go" }, StringSplitOptions.None))
.ToList();
Parallel.ForEach(list, (sql) =>
{
using (var mysqlConn = new SqlConnection("Server=.;Integrated security=SSPI;database=master"))
{
var mysql = "USE [" + databaseName + "]" + Environment.NewLine + string.Join("", sql);
var mysqlCommand = new SqlCommand(mysql, mysqlConn);
myConn.Open();
mysqlCommand.ExecuteNonQuery();
}
});
//server.ConnectionContext.ExecuteNonQuery(readtext);
return true;
}
catch (Exception e)
{
throw e;
return false;
}
}
The problem was in Go Keyword in script, I Found this solution
http://www.codingdefined.com/2014/07/run-sql-script-file-in-c.html
(If you are trying to execute a SQL generated script file you have to remove all "GO". For that you have to use the following code...)
Here is my code:
string sqlConnectionString = "Data Source=.;Initial Catalog=master;Integrated Security=True";
FileInfo file = new FileInfo(#"D:\Script.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
conn.Open();
script = script.Replace("GO", "");
SqlCommand cmd = new SqlCommand(script, conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();

Having SQL Syntax error in c#

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.

SQL Insert not working

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

SQLite and delete command

bool ret = false;
try
{
SQLiteConnection sqlConn = new SQLiteConnection("Data Source=" + m_dbName);
sqlConn.Open();
SQLiteCommand sqlComm = sqlConn.CreateCommand();
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name="+name+"";
SQLiteDataAdapter sqlAdapter = new SQLiteDataAdapter(sqlComm);
if (null == sqlAdapter)
{
ret = false;
}
else
{
ret = true;
}
sqlConn.Close();
return ret;
}
catch (SQLiteException sqlEx)
{
Console.WriteLine(sqlEx.Message);
return false ;
}
I have that code to delete a row in an sqlite database, but nothing is done after I click the delete button.
Instead of using a DataAdapter you could just execute the command directly:
using(SQLiteConnection sqlConn = new SQLiteConnection("Data Source=" + m_dbName))
{
sqlConn.Open();
//create command
sqlCommand.ExecuteNonQuery();
}
You shouldn't swallow any exceptions that get thrown from the ExecuteNonQuery method unless you can sensibly handle them. You should use parameterised queries instead of manually creating the queries by concatenating strings. You should also make sure you close the connection after you have finished using it as shown.
Try with single quotes:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name='"+name+"'";
Have you tried using like instead of =
inside the query:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name="+name+""
as this:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name like "+name+""
using (SQLiteCommand com = new SQLiteCommand(con))
{
com.CommandText = "DELETE FROM " + szTablename + " WHERE name='" + name + "';";
com.ExecuteNonQuery();
com.Dispose();
}

Problem with multiple SqlDataReader and SqlCommand in a Class

I have a problem with C#, I have a Class with a function for SqlDataReader and another for SqlCommand (the first one is just for read values from a DataBase and the second one is for INSERT, UPDATE, DELETE ... in the same DB).
The problem is, for the first part of the code (the login), I have to search the values from an Active Directory (it works), then I must see if the user has username and password in my own DB (it works), and then, if the user is not in the DB then I have to create it and get the ID, if it is already created then I just have to get the ID.
The problem is that I get this message :
InvalidOperationException was
unhandled by user code
There already exist an Open DataReader
associated with this Command, who as
to be closed first.
There is the code :
Class.cs :
private static string MyConnectionString = "THIS IS MY CONNECTION";
private SqlConnection MyConnection = new SqlConnection(MyConnectionString);
public SqlCommand MyCommand = new SqlCommand();
public SqlDataReader MyReader = null;
public void DBMyReader(String SqlQuery)
{
if (MyConnection.State != ConnectionState.Open)
MyConnection.Open();
MyCommand.Connection = MyConnection;
MyCommand.CommandText = SqlQuery;
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
public void DBMyUpdate(String SqlQuery)
{
if (MyConnection.State != ConnectionState.Open)
MyConnection.Open();
var cmdTest = new SqlCommand();
cmdTest.Connection = MyConnection;
cmdTest.CommandText = SqlQuery;
cmdTest.ExecuteNonQuery();
}
public void DBMyInsert(String SqlQuery)
{
DBMyUpdate(SqlQuery);
}
** Login.aspx.cs: **
MyClass.DBMyReader("SELECT util_codi,util_logi,util_nome FROM Tgep_util WHERE util_logi='"
+ Session["username"].ToString() + "'");
MyClass.MyReader.Read();
if (!MyClass.MyReader.HasRows)
{
MyClass.MyReader.Close();
MyClass.DBMyInsert("INSERT INTO Tgep_util(util_logi,util_nome) "
+ "VALUES ('" + Session["username"].ToString() + "','" + Session["nome"].ToString() + "')");
}
MyClass.DBMyReader("SELECT util_codi,util_logi,util_nome FROM Tgep_util WHERE util_logi='"
+ Session["username"].ToString() + "'");
MyClass.MyReader.Read();
Session["user_id"] = MyClass.MyReader["util_codi"].ToString();
Response.Redirect("FRM_Principal.aspx");
Edit : Update Code (Works for now)
The error means exactly what it says.. You have loaded a SQLCommand and started reading rows, and are now trying to do an insert. You need to close out that reader first, or use a new command.
in the DBMyUpdate function you could just create a new command:
public void DBMyUpdate(String SqlQuery)
{
if (MyConnection.State != ConnectionState.Open)
MyConnection.Open();
var cmdUpdate = new SqlCommand();
cmdUpdate.Connection = MyConnection;
cmdUpdate.CommandText = SqlQuery;
cmdUpdate.ExecuteNonQuery(CommandBehavior.CloseConnection);
}
edit: based on comments to this answer, it required using separate connections which seems odd/incorrect.
You can't use the same DataReader for insert/update that you used for insertion. You have to close the DataReader first before associating some other command with the DataReader.

Categories

Resources