Query Multiple Databases SQL Server - c#

I'm having a problem running a query across multiple databases on an Azure SQL Server. This is the function I have made to return a DataTable from the query once it has been executed. The function takes the database name as a string and inserts it into the conenction string, along with the query to be executed.
The function works fine when I run it once, returning the DataTable populated with returned rows as intended, but when I call the function using a 'foreach' statement (Iterating through a list of database names) I get a timeout error or a login failed error.
Any help on this would be appreciated.
public static DataTable runQuery(String db, String query)
{
using (SqlConnection con = new SqlConnection("Data Source=server.database.windows.net;Initial Catalog=" + db + ";User ID=user#server;Password=password"))
{
con.Open();
using (DataTable dt = new DataTable())
{
try
{
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.Dispose();
da.Dispose();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
return dt;
}
}
}

Add cmd.CommandTimeout = 0
try
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandTimeout = 0;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtt);
cmd.Dispose();
da.Dispose();
}

I think you should try adding System.Threading.Thread.Sleep inside the foreach block.

Related

Getting output from return type DataSet and displaying it in a Gridview

I am trying to get the output from a method with return type as DataSet and using it in a GridView but the output is not reflecting.
Can anyone please advice how to get the output.
public DataSet GetData()
{
try
{
SqlConnection conn = new SqlConnection(connectionString);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
String sql = "Select top 100 * from SEQUENCE";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet output = new DataSet();
adapter.Fill(output);
conn.Close();
return (output);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", ex.Message, true);
return (null);
}
}
Home home = new Home();
Output=home.GetData();
GridViewOutput.DataSource = Output.Tables["Out"];
GridViewOutput.DataBind();
Try moving where you declared output and returned it, to as shown bellow.
I changed the part where you declare the grid views data source. You should be able to just declare the datasets datasource as the method itself.
Have a look at this thread on dataset vs datatable Datatable vs Dataset
A DataSet can hold multiple tables. However if you're just returning a single results set a DataTable rather than a DataSet would probably make more sense.
Just change the Methods type to a DataTable. Declare it's source the same way as shown bellow.
public DataSet GetData()
{
//Move where you declare output ot here
DataSet output = new DataSet();
try
{
SqlConnection conn = new SqlConnection(connectionString);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
String sql = "Select top 100 * from SEQUENCE";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(output);
conn.Close();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", ex.Message, true);
return (null);
}
//And move the return to here
return output;
}
//Should just need this to display the data
GridViewOutput.DataSource = GetData();
GridViewOutput.DataBind();
One final thing when using SQL in c# I tend to use the using statement. It makes the code a lot cleaner and handles the disposing of resources for you see When should I use the using Statement? . Your code would look like this if you choose to use it:
public DataTable GetData()
{
//Move where you declare output ot here
var output = new DataTable();
using (var conn = new SqlConnection())
{
try
{
conn.ConnectionString = //Your DataBase Connection;
String sql = "Select top 100 * from SEQUENCE";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.commandType = commandType.Text;
Var adapter = new SqlDataAdapter(cmd);
adapter.Fill(output);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", ex.Message, true);
return (null);
}
//And move the return to here
return output;
}
}
//Should just need this to display the data
GridViewOutput.DataSource = GetData();
GridViewOutput.DataBind();

Oracle database table in gridview

I want to get the result from a query in my oracle database and put it in a gridview. Now my problem is, I have no idea how to output it in the gridview. I am using the gridview from the toolbox and my oracle connection is working. I also have the right SELECT query and I can output that in a listbox. I just have no idea how to do this in a gridview. I looked for it and I came across this: How to populate gridview with mysql? Although this doesn't help me.
How can I output it in a gridview so that it looks exactly the same as a normal table in the oracle database?
What should I use and how?
This is my code:
public void read()
{
try
{
var conn = new OracleConnection("")
conn.Open();
OracleCommand cmd = new OracleCommand("select * from t1", conn);
OracleDataReader reader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
while (reader.Read())
{
var column1 = reader["vermogen"];
column = (column1.ToString());
listBox1.Items.Add(column);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To bind a DataTable to a DataGridView your code need simply to be changed to
public void read()
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The OracleDataReader could be passed to the Load method of the DataTable and then the table is ready to be bound to the DataGridView DataSource property. I have also added some using statement to ensure proper disposing of the disposable objects employed. (In particular the OracleConnection is very expensive to not close in case of exceptions)
You can use DataSet too:
public void read()
{
try
{
OracleConnection conn = new OracleConnection("");
OracleCommand cmd = new OracleCommand("select * from t1", conn);
conn.Open();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
First establish connection in case, you didnt establish globally by using connection string. Then use oleDbcommand for the oracle sql command you want to execute. In my case, it is 'select * from table_name' which would show all data from table to datagrid. I wrote this code in a button to display data on data grid.
{
OleDbConnection conn = new OleDbConnection("");
OleDbCommand cmd = new OleDbCommand("select * from table_name", conn);
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
conn.Close();
}
}

sql command timeout potential issue

How is it I can upload a 20+ mb file to a webserver, but have it timeout when I try to download it? I would think the upload would timeout as well.
Both are using ado.net sqlclient. The event log shows SqlException timeout occurred when attempting to download.
This article looks like a possible lead. But again, why wouldn't it timeout on the upload?
public DataTable ExecuteDataTable(string sql)
{
SqlConnection conn = new SqlConnection();
DataTable dt;
try
{
conn.Open();
SqlCommand dateformatcmd = new SqlCommand("set dateformat " + myDateFormat, conn);
dateformatcmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
SqlCommand cmd = new SqlCommand(sql, conn);
//Walk through the parameters
foreach (string name in param.Keys)
{
cmd.Parameters.Add(new SqlParameter(name, param[name]));
}
da.SelectCommand = cmd;
dt = new DataTable();
da.Fill(dt);
}
catch (SqlException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return dt;
}

How I Reload Datagridview data while insert or update data in .net form application and database is in access database?

I have a desktop application project. In entry page a datagridview shows the existing items in database. Now when I entry new Item I want to insert it directly in datagridview. That mean I want to reload/refresh datagridview. My database is in MS Access.
private DataTable GetData()
{
DataTable dt = new DataTable();
//using (SqlConnection con = new SqlConnection(conn))
using (OleDbConnection con=new OleDbConnection(conn))
{
OleDbCommand cmd = new OleDbCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
//SqlCommand cmd = new SqlCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
con.Open();
//SqlDataAdapter ad = new SqlDataAdapter(cmd);
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
return dt;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(conn);
OleDbConnection con = new OleDbConnection(conn);
con.Open();
//SqlCommand cmd;
try
{
string query = "insert into GroupDetails (ID,Name) values(#ID,#Name)";
// cmd = new SqlCommand(query,con);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#ID",txtID.Text);
cmd.Parameters.AddWithValue("#Name",txtName.Text);
int i = cmd.ExecuteNonQuery();
if(i!=0)
{
dataGridGroup.DataSource = GetData();
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
con.Close();
}
}
[Note: When I use sql database then it works fine.]
The dbDataAdapterClass (the one that OleDbDataAdapter inherits from) has a SelectCommand, UpdateCommand and InsertCommand. These are responsible for select, update, and insert when you explicit call any of the methods (for example update ;) ). Since in your code, you never provide the command that explain how to do the update, the dataadapter doesn't know how to do it.
so fulfill the requirements, adding an update command to the adapter.
dataadapter = new OleDbDataAdapter(sql, connection);
Add below code after above line, OleDbCommandBuilder will generate commands for you.
OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadapter);
This tutorial should help you out.

Rollback changes when code not executed properly

I am new to SQL, In my project I am trying to fill the DataSet from the DataBase table and then inserting new rows in DataSet. After doing this, again I am filling the Database table with the DataSet data. Before filling I am clearing or deleting the Database table data. Well I achieved this by using the below code:
Database Table --> myTable
DataSet --> ds
OnButtonClick
string strQuery = "delete from [dbo].[myTable]"
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlCommand command;
SqlDataAdapter da = new SqlDataAdapter(cmd);
using (cmd)
{
using (conn)
{
conn.Open();
cmd.ExecuteNonQuery(); //deleting database table data
foreach (DataRow dr in ds.Tables[0].Rows) //Inserting new data into the Database table
{
command = new SqlCommand(InsertQuery, conn);
command.ExecuteNonQuery();
}
conn.Close();
}
}
The above code is working fine but when there is any exception in command sqlCommand then it is deleting the database table completely and not filling the DataSet. Any suggestions to modify this code? please help.
UPDATE:
string strQuery = "delete from [dbo].[myTable]";
using (SqlCommand cmd = new SqlCommand(strQuery, conn))
{
using (SqlCommand cmdReset = new SqlCommand("DBCC CHECKIDENT('myTable', RESEED, 0)", conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
cmd.Transaction = sqlTransaction;
try
{
cmd.ExecuteNonQuery(); //deleting database table data
cmdReset.ExecuteNonQuery(); //Resetting Identity of first column
foreach (DataRow dr in ds.Tables[0].Rows) //Inserting new data into the Database table
{
command = new SqlCommand(query.createDoctorRow(InsertQuery, conn);
command.ExecuteNonQuery();
}
sqlTransaction.Commit();
conn.Close();
}
catch (Exception e)
{
sqlTransaction.Rollback();
/*ERROR*/ throw;
}
}
}
ERROR --> "ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized."
Use a transaction to run the sql
string strQuery = "delete from [dbo].[myTable]";
using (SqlConnection conn = new SqlConnection(strConn))
{
using (cmd = new SqlCommand(strQuery, conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
cmd.Transaction = sqlTransaction;
try
{
cmd.ExecuteNonQuery(); //deleting database table data
foreach (DataRow dr in ds.Tables[0].Rows) //Inserting new data into the Database table
{
command = new SqlCommand(InsertQuery, conn);
command.ExecuteNonQuery();
}
sqlTransaction.Commit();
conn.Close();
}
catch(Exception e)
{
sqlTransaction.Rollback();
throw;
}
}
}
Transactions form an all or nothing scenario. Either everything in the transaction works and is committed to the database, or the whole lot is cancelled as if nothing happened.
This example has a nice way of wrapping sql commands in a transaction scope. Basically if any exception is thrown during any of the row insert the delete query will fail as well.
In a nut shell you wrap everything inside a
using (TransactionScope scope = new TransactionScope())
{
using (SqlConnection connection1 = new SqlConnection(connectString1))
{
//enter your code here
}
}
Also you don't have to do an insert row by row you can use the SqlBulkCopy to do it more efficiently.
using (SqlConnection connection =new SqlConnection(connectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName = table.TableName;
bulkCopy.WriteToServer(table);
}
}

Categories

Resources