I am trying to insert huge multiple rows in a single transaction. But the SQL Server database is not getting reflected with the update. Below is my code snippet. What am I doing wrong?
private void Form1_Load(object sender, EventArgs e)
{
string conString = Properties.Settings.Default.Database1ConnectionString;
Database1DataSet.Table1DataTable dt = new Database1DataSet.Table1DataTable();
for (int i = 0; i < 5; i++)
{
dt.AddTable1Row(i.ToString(), "name" + i.ToString());
}
// Open the connection using the connection string.
using (SqlCeConnection con = new SqlCeConnection(conString))
{
try
{
var cmd = con.CreateCommand();
con.Open();
cmd.CommandType = CommandType.TableDirect;
cmd.CommandText = "Table1";
var rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable)
var rec = rs.CreateRecord();
foreach (DataRow dr in dt.Rows)
{
rec.SetString(0, dr["ID"].ToString());
rec.SetString(1, dr["Name"].ToString());
rs.Insert(rec);
}
rs.Close();
rs.Dispose();
cmd.Dispose();
}
catch (Exception ex) { }
}
}
You are facing this: http://erikej.blogspot.com/2010/05/faq-why-does-my-changes-not-get-saved.html
Related
I am trying to use a SqlDataReader to run queries on two tables where the 1st column in the Selection table is a foreign key referencing to the Items table, and then display the results in labels, but I keep getting the error:
Invalid attempt to read when no data is present.
Here is my code:
public partial class Read : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"data source = localhost; integrated security = true; database = dev_handin1");
SqlCommand cmd = null;
SqlDataReader rdr = null;
string sqlsel = "SELECT MainItemId FROM Selection";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetInfo();
}
}
private void GetInfo() {
try
{
cmd = new SqlCommand(sqlsel, conn);
conn.Open();
sqlsel = "SELECT * FROM Items WHERE ItemId = MyMainItem";
rdr = cmd.ExecuteReader();
var MyMainItem = rdr[0];
while (rdr.Read())
{
LabelCategory1.Text = rdr[1].ToString();
LabelHeadline1.Text = rdr[2].ToString();
LabelText1.Text = rdr[3].ToString();
LabelJoke1.Text = rdr[4].ToString();
}
}
catch (Exception ex)
{
LabelMessage1.Text = ex.Message;
}
finally
{
rdr.Close();
conn.Close();
}
}
}
}
I'm pretty new at this so please bear with me.
When i use the code below,it does delete a row from a datagridview but when i refresh the page it does not..
private void DeleteData_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Selected)
{
dataGridView1.Rows.RemoveAt(row.Index);
break;
}
using (SqlConnection sqcon = new SqlConnection(#"MY CONNECTION STRING"))
{
SqlCommand Scmd = new SqlCommand();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow delrow = dataGridView1.Rows[i];
if (delrow.Selected == true)
{
dataGridView1.Rows.RemoveAt(i);
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + (i++) + "";
sqcon.Open(); //ADDED
int count = Scmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
What should i use to delete row from both local database and datagridview?
i think the connection not be assigned to the command object.
SqlCommand Scmd = new SqlCommand();
Scmd.Connection = sqcon;
also i preferred to use DataGridView.SelectedRows instead of looping all records in grid.
full code
private void DeleteData_Click(object sender, EventArgs e)
{
var rowsToDelete = dataGridView1.SelectedRows;
using (SqlConnection sqcon = new SqlConnection(#"MY CONNECTION STRING"))
{
SqlCommand Scmd = new SqlCommand();
Scmd.Connection = sqcon;
sqcon.Open(); //ADDED
foreach (DataGridViewRow row in rowsToDelete)
{
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + row.Cells["Id"].Value.ToString() + "";
int count = Scmd.ExecuteNonQuery();
dataGridView1.Rows.Remove(row);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
sqcon.Close();
}
}
Try this,
Delete from database use the unique column or the Id column.
//Make datagridview cell[0] the unique column in your table.
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID='" + datagridview.rows[i].cell[0].value + "'";
sqcon.Open(); //ADDED
int count = Scmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I would like to see all of the data with column names in my logfile.
private static void ExecuteSQL()
{
string conn = "User ID=SYSDBA;Password=masterkey;Database=XX.18.137.XXX:C:/ER.TDB;DataSource==XX.18.137.XXX;Charset=NONE;";
FbConnection myConnection = new FbConnection(conn);
FbDataReader myReader = null;
string sql = "SELECT * FROM RDB$RELATIONS";
FbCommand myCommand = new FbCommand(sql, myConnection);
try
{
myConnection.Open();
myCommand.CommandTimeout = 0;
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
// Log.WriteLog(myReader["rdb$relation_name"].ToString());
}
myConnection.Close();
}
catch (Exception e)
{
Log.WriteLog(e.ToString());
}
}
Right now it's only showing me the rdb$relation_name column.
I want to check the different tables for which I don't have the column's name.
All you need to do is iterate over all fields printing their names before iterating the results:
private static void ExecuteSQL()
{
string conn = "User ID=SYSDBA;Password=masterkey;Database=XX.18.137.XXX:C:/ER.TDB;DataSource==XX.18.137.XXX;Charset=NONE;";
FbConnection myConnection = new FbConnection(conn);
FbDataReader myReader = null;
string sql = "SELECT * FROM RDB$RELATIONS";
FbCommand myCommand = new FbCommand(sql, myConnection);
try
{
myConnection.Open();
myCommand.CommandTimeout = 0;
myReader = myCommand.ExecuteReader();
// 1. print all field names
for (int i = 0; i < myReader.FieldCount; i++)
{
Log.WriteLog(myReader.GetName(i));
}
// 2. print each record
while (myReader.Read())
{
// 3. for each record, print every field value
for (int i = 0; i < myReader.FieldCount; i++)
{
Log.WriteLog(myReader[i].ToString());
}
}
myConnection.Close();
}
catch (Exception e)
{
Log.WriteLog(e.ToString());
}
}
I am pretty sure, that this will give ugly output as it prints every output to a new line. You should be able to change this to print the fields and each record in rows.
public static List<string> GetColumnNames(string queryString)
{
string result = string.Empty;
List<string> listOfColumns = new List<string>();
try
{
using (FbConnection conn = new FbConnection(connString))
{
conn.Open();
using (FbCommand cmd = new FbCommand(queryString, conn))
{
// Call Read before accessing data.
FbDataReader reader = cmd.ExecuteReader();
if (reader.FieldCount > 0)
{
for (int i = 0; i < reader.FieldCount; i++)
{
listOfColumns.Add(reader.GetName(i));
}
}
}
}
}
catch (Exception e)
{
BinwatchLogging.Log(e);
}
return listOfColumns;
// return result;
}
where querystring is your query (eg: select * from yourtablename) and connstring is your firebird connectionstring
I need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
first time on stackoverflow.
I'm learning how to manage SqlConnection in my WebForm pages, and I want to reach the best practice to do that.
In my specific case, I have a loop and there's no way for me to run the code without errors if I don't set a new SqlConnection for every iteration of the loop (the error is about an attempt to read when reader is close).
So I declare this in the PageLoad method:
private SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(connectionString);
}
Then I have this:
private int conta(int padre)
{
string SQL = "SELECT * FROM categories WHERE idp=#idpadre";
SqlCommand cd = new SqlCommand(SQL, con);
cd.Parameters.AddWithValue("#idpadre", padre);
int sub=0;
try
{
if ((con.State & ConnectionState.Open) <= 0)
{
con.Open();
}
using (SqlDataReader reader = cd.ExecuteReader())
{
while (reader.Read())
{
sub++;
}
}
}
catch (Exception err)
{
lbl.Text = "Errore conta!";
lbl.Text += err.Message;
}
finally
{
con.Close();
}
return sub;
}
protected void buildParent(int padre, int level)
{
StringBuilder sb = new StringBuilder();
sb.Append(" ");
for (int i = 0; i < level; i++)
{
sb.Append(HttpUtility.HtmlDecode(" "));
}
sb.Append("|--");
selectSQL = "SELECT * FROM categories WHERE idp=#idpadre";
SqlConnection cn = new SqlConnection(connectionString);
cmd = new SqlCommand(selectSQL, cn);
cmd.Parameters.AddWithValue("#idpadre", padre);
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
dlParent.Items.Add(new ListItem { Text = sb.ToString() + read["cat"].ToString(), Value = read["idcat"].ToString() });
int sub = conta(Convert.ToInt32(read["idcat"]));
//int sub = 0;
if (sub > 0)
{
buildParent(Convert.ToInt32(read["idcat"]), level + 1);
}
}
read.Close();
}
}
catch (Exception err)
{
lbl.Text = "Errore buildParent!";
lbl.Text += err.Message;
}
finally
{
cn.Close();
if (s != null)
{
if (!this.IsPostBack)
{
buildPage();
buildLang();
buildImage();
}
}
}
}
In buildParent in the while loop i call "conta", but if I use the same SqlConnection (con) with both the methods I have an error about an attempt to read when reader is close.
I'm worried about the connection pool on the web server, particularly concerning the max connection reach.
So, where am I wrong? What's the best practice to manage SqlConnection?
Thank you.
You open the connection as late as possible, and you dispose as soon as possible. Let the connection pool deal with reclaiming the connections.
I usually write my code like this:
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(commandToRun, conn))
{
cmd.Parameters.AddRange(new[]
{
new SqlParameter("myParam", "myvalue"),
new SqlParameter("myParam", "myvalue")
});
conn.Open(); // opened as late as possible
using (SqlDataReader reader = cd.ExecuteReader())
{
while (reader.Read())
{
// do stuff.
}
}
} // disposed here.
Note: To get a count from a SQL database you better use
SELECT count(*) FROM categories WHERE idp=#idpadre
And execute the query with ExecuteScalar()