Another question today. This time, I'm having trouble deleting a row from a SQL Server CE database.
private void Form1_Load(object sender, EventArgs e)
{
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\userDtbs.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("SELECT * FROM history", connection);
DataSet data = new DataSet();
adapter.Fill(data);
//Delete from the database
using (SqlCeCommand com = new SqlCeCommand("DELETE FROM accounts WHERE Id = 0", connection))
{
com.ExecuteNonQuery();
}
// Save data back to the databasefile
var cmd = new SqlCeCommandBuilder(adapter);
adapter.Update(data);
// Close
connection.Close();
}
My program's giving me an error telling me that connection is in a closed state, and I can't figure out why it would close before the DELETE command is executed.
Note that: executing command with Command.ExecuteXXX() requires the connection to be open first. Filling data into DataSet using SqlDataAdapter.Fill doesn't require that because it handles that internally. Executing the SQL query this way is direct and don't require any Update method call on adapter (as you add in your code after deleting). Update is just for saving changes made on your DataSet.
//Delete from the database
using (SqlCeCommand com = new SqlCeCommand("DELETE FROM accounts WHERE Id = 0", connection))
{
if(connection.State == ConnectionState.Closed) connection.Open();
com.ExecuteNonQuery();
}
Related
What I have:
MS VS 2017
MySql server launched on local host
Completely installed pack mysql-installer-community-8.0.15.0.msi
What I need:
To create a Windows Forms application using an element DataGridView,
whith bound table columns. I suppose that
this radio-button should be active to do it
The problem I've faced
When I drag an element DataGridView on a form the function of binding table columns is blocked. As far as I understood, I have not connected to my database correctly, however the following code works (that means that connection has been estabilished)
static void Main(string[] args)
{
string connectionString = "server=localhost;user=root;database=mydatabase;password=mypassword";
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
string sql = "SELECT id, last_name FROM people WHERE id < 300";
MySqlCommand command = new MySqlCommand(sql, conn);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString() + " " + reader[1].ToString());
}
conn.Close();
}
What I tried
this solution do not works for me
created new user account in database
re-created connection
Why are you using code for Consol Application?
If you want to use dataGridView use Load event of your form:
private void Form1_Load(object sender, EventArgs e)
{
string connectionString = "server=localhost;user=root;database=mydatabase;password=mypassword";
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
string sql = "SELECT id, last_name FROM people";
MySqlCommand command = new MySqlCommand(sql, conn);
MySqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
dataGridView1.Rows.Add((string)reader["id"], (string)reader["last_name"]);
i++;
}
conn.Close();
}
In my business logic, I use multiple oracle query's multiple times. What is the best way to open and close the oracle connection?
private void update()
{
OracleConnection con = new OracleConnection("Connection Statement");
OracleCommand command = new OracleCommand("Select Statement");
con.Open();
OracleDataReader reader = command.ExecuteReader();
reader.Close();
con.Close();
// A for loop
con.Open();
command = new OracleCommand("Update statement");
command.ExecuteNonQuery();
con.Close();
con.Open();
command = new OracleCommand("Second Update statement");
command.ExecuteNonQuery();
con.Close();
}
My code looks like this. Should I open and close my oracle connection for every command or open before the first command and close after the last command.
P.S. This update function is called over 100 times in my application.
As the connection is local to the method create it in a using block and then use it as many times as you need to in that block. The block can contain loops or whatever, there is no rule that states you have to discard the connection after you use it once.
However connection sharing is discouraged, so do not create a class level instance or static instance for shared use.
private void update()
{
using(OracleConnection con = new OracleConnection("Connection Statement"))
{
con.Open();
using(var command = new OracleCommand("Select Statement", con))
using(OracleDataReader reader = command.ExecuteReader()}
{
}
// A for loop
using(var command = new OracleCommand("Update statement", con))
{
command.ExecuteNonQuery();
}
using(var command = new OracleCommand("Second Update statement", con))
{
command.ExecuteNonQuery();
}
}
}
I am using Windows application c#. When I bind the data table to Datagridview it gets slow and I am getting a SQL connection timeout error.
At the same time my data table has bulk records. How can I solve this problem?
Code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
con.StatisticsEnabled = true;
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("select * from Stktrn_table", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
GridDisplay.ItemsSource = dt.DefaultView;
}
SqlCommand cmdVoid = new SqlCommand("select party_no, smas_rtno,convert(numeric(18,2),SUM(smas_NetAmount)) as Amount from salmas_table where ctr_no=#tCounter and Smas_Cancel<>1 and smas_rtno<>0 and Smas_billdate=#tDate group by smas_rtno, party_no", con);
cmdVoid.Parameters.AddWithValue("#tDate", dpBillDate.SelectedDate.Value);
cmdVoid.Parameters.AddWithValue("#tCounter", tCounterNoNew);
SqlDataAdapter adpVoid = new SqlDataAdapter(cmdVoid);
adpVoid.Fill(dtVoid);
This line
SqlCommand cmd = new SqlCommand("select * from Stktrn_table", con);
Will be your problem. Do not select all rows from the database, limit it using TOP
SELECT TOP 100 Column1, Column2, Column3 FROM Stktrn_table
in general SELECT * is bad practice.
Or alternatively, implement paging so the rows are loaded on demand rather than upfront.
How does the query run within SQL Server management studio? This should be your initial indicator of how long the query will return from the database.
You could also use a stored procedure which may give you a performance benefit over a raw SQL query.
First thing You should not use like this Select * from table_name instead this you should use select column_1,column_2,column3,column_n i.e. select only columns which you needed.
Second thing always use classes(BLL and DLL) instead of coding directly for database at page load or any form.
Third always use try catch block.
Third thing whenever you create a object, you should dispose that in finally block of try catch.
for ex.
DataTable dt = null;
SqlDataAdapter da = null;
SqlConnection con = null;
try
{
con=new SqlConnection("Connection_Source");
con.Open();
da = new DataAdapter("select * from table_name",con);
dt=new DataTable();
da.Fill(dt);
dataGridViewObj.DataSource=dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(con.State==ConnectionState.Open)
con.Close();
dt.Dispose();
if(dt!=null)
dt=null;
da.Dispose();
if(da!=null) da=null;
}
i have problem with sqlite !
in my c# app i using a little database based on sqlite, i can select and see database data but the problem is that and when i try to insert a record into the table i see it in the program and it's worked well but and added to my DB but when i close the program and open the DB nothing saved :( and when i'm using my app this seems it's added to database but in realtime i'm using firefox addons to see database or when close and open app nothing saved.
SQLiteConnection ObjConnection = new SQLiteConnection("Data Source=Data/data.db3;");
private void button1_Click(object sender, EventArgs e)
{
SQLiteCommand ObjCommand = new SQLiteCommand("SELECT * FROM PERSON", ObjConnection);
ObjCommand.CommandType = CommandType.Text;
SQLiteDataAdapter ObjDataAdapter = new SQLiteDataAdapter(ObjCommand);
DataSet dataSet = new DataSet();
ObjDataAdapter.Fill(dataSet, "Person");
dataGridView1.DataSource = dataSet.Tables["Person"];
}
private void button2_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
string last = textBox2.Text;
string q1 = "INSERT INTO Person(Firstname,Lastname) VALUES(?,?)";
SQLiteCommand cmd1 = new SQLiteCommand(q1, ObjConnection);
cmd1.Parameters.AddWithValue("#SongName",name);
cmd1.Parameters.AddWithValue("#ArtistName",last);
ObjConnection.Open();
cmd1.ExecuteNonQuery();
ObjConnection.Close();
SQLiteCommand ObjCommand = new SQLiteCommand("SELECT * FROM PERSON", ObjConnection);
ObjCommand.CommandType = CommandType.Text;
SQLiteDataAdapter ObjDataAdapter = new SQLiteDataAdapter(ObjCommand);
DataSet dataSet = new DataSet();
ObjDataAdapter.Fill(dataSet, "Person");
dataGridView1.DataSource = dataSet.Tables["Person"];
}
private void button3_Click(object sender, EventArgs e)
{
ObjConnection.Open();
ObjConnection.ChangePassword("123");
ObjConnection.Close();
}
It seems a problem with the connection String, SQLite would be using in your case a temporary database. Temporary Databases are automatically deleted when the connection that created them closes.
Data Source=Data/data.db3;
Just to discard my solution, could you try with an exiting absolute path (c:\Data):
Data Source=c:\\Data\\data.db3;
I am working on WPF application in C#. Database is SQL Server 2008. I have a table "Employee" in database, I need to insert a row in it. I have successfully connected with database, but when I tried to execute this line:
cmd = new SqlCommand(cmdText, conn);
This errors comes up: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(String, System.Data.SqlClient.SqlConnection)' has some invalid arguments.
Here is my code:
private void addbtn_Click(object sender, RoutedEventArgs e)
{
//FUNCTION TO ADD NEW EMPLOYEE RECORD IN DATABASE
try
{
conn.ConnectionString = "Data Source=AZEEMPC;" + "Initial Catalog=IEPL_Attendance_DB;";
conn.Open();
cmdText = "INSERT INTO Employee VALUES ('" + strCurrentString + "','" + emp_name.Text + "')";
cmd = new SqlCommand(cmdText, conn);
data_ad = new SqlDataAdapter(cmd);
data = new DataSet();
data_ad.Fill(data);
MessageBox.Show("Record Inserted Successfully!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any suggestions?
conn needs to be of type SqlConnection - can you confirm that it is?
SqlConnection conn;
Because it's a native SQL Server connection, you don't need to pass the driver name in the connection string.
conn.ConnectionString = "Server=AZEEMPC;Database=IEPL_Attendance_DB;Trusted_Connection=true;";