What is the code with the smallest number of lines that will generate a DataTable from this SQL query?
SELECT *
FROM [Table1]
WHERE ([Date] BETWEEN #Date1 AND #Date2) AND
([Field1] IS NULL OR [Field2] IS NULL)
Use SqlDataAdapter to fill a DataTable.
DataTable dt = new DataTable();
using (SqlConnection yourConnection = new SqlConnection("connectionstring"))
{
using (SqlCommand cmd = new SqlCommand("....your sql statement", yourConnection))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
Use using block with your SqlConnection, SqlCommand and SqlDataAdapter since they implement IDisposable interface. Also use Parameterized query
Try this
SqlCommand command = new SqlCommand(query, conn);
DataTable dt = new DataTable();
using(SqlDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
SqlDataAdaptor and FillSchema
It will create your table on the fly
Applied On a DataSet
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx
Applied On a DataTable
http://msdn.microsoft.com/en-us/library/152bda9x.aspx
Related
When I add data to my SQLite database table using the below code, it adds 2 identical rows to the table for some reason instead of one.
using(SQLiteConnection conn= new SQLiteConnection(#"Data Source="+Path.GetFullPath("./TestDB.db")+";"))
{
conn.Open();
SQLiteCommand command = new SQLiteCommand("INSERT INTO Test(FirstName, LastName, Age) VALUES('Chris','Pine',42)", conn);
command.ExecuteNonQuery();
SQLiteDataAdapter adap = new SQLiteDataAdapter(command);
DataTable dt = new DataTable("Test");
adap.Fill(dt);
dataGrid1.ItemsSource=dt.DefaultView;
adap.Update(dt);
conn.Close();
}
MessageBox.Show("Complete!");
refreshdata();
Why is this happening ?
Also, the code for refreshdata
public void refreshdata()
{
using(SQLiteConnection conn= new SQLiteConnection(#"Data Source="+Path.GetFullPath("./TestDB.db")+";"))
{
conn.Open();
SQLiteCommand command = new SQLiteCommand("Select * from Test", conn);
command.ExecuteNonQuery();
SQLiteDataAdapter adap = new SQLiteDataAdapter(command);
DataTable dt = new DataTable("Test");
adap.Fill(dt);
dataGrid1.ItemsSource=dt.DefaultView;
adap.Update(dt);
conn.Close();
}
You are calling ExecuteNonQuery and you are giving the adapter an INSERT command in place of its SelectCommand.
SQLiteDataAdapter adap = new SQLiteDataAdapter(command);
That line of code uses a the constructor that sets the adapter's SelectCommand. When you Fill() the datatable, it calls the SelectCommand, but in your case it is an INSERT statement.
Really, you should not be doing anything with an Adapter there, you should just ExecuteNonQuery and then call refreshdata.
And you can remove the call to Update() in refreshdata(), it is not necessary.
This is a sample query:
declare #tempTable table
(
Id bigint
)
-- populating with temp Ids
select *
from TargetTable
where Id not in
(
select Id
from #tempTable
)
And this is C# code:
public DataTable Get(string sql)
{
var dataTable = new DataTable();
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand())
{
connection.Open();
command.Connection = connection;
command.CommandText = sql;
var dataReader = command.ExecuteReader();
dataTable.Load(dataReader);
}
return dataTable;
}
Running this code throws exception, complaining that:
Incorrect syntax near the keyword 'declare'.
Incorrect syntax near
')'.
I know it's possible to use join instead of #tempTable, but is there a way to run this query?
A SqlDataAdapter object can be used to populate a DataTable as follows. Instead of calling SqlCommand.ExecuteReader(), the SqlDataAdapter.Fill() method is used. In this example the argument to the Fill() method is the DataTable that will be populated. While this approach will work with the query you posted with the table variable, I'd strongly recommend converting this to a stored procedure and filling the DataTable from this instead. Additionally, unless the amount of data that's being sent into the table variable is very small using a temp table will offer more functionality (more accurate statistics, better DML performance, ROLLBACK participation, etc.) than table variables and I'd suggest using a temp table instead as well.
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataTable dataTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand command = new SqlCommand(cmd, connection);
da.SelectCommand = command;
connection.Open();
da.Fill(dataTable);
}
Stored Procedure Call:
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataTable dataTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
//use SP name for command text
SqlCommand command = new SqlCommand("usp_ProcedureName", connection);
//stored procedure command type
command.CommandType = CommandType.StoredProcedure;
da.SelectCommand = command;
connection.Open();
da.Fill(dataTable);
}
You can create a Stored Procedure of your query then add this to your code:
command.CommandType = CommandType.StoredProcedure;
Then use exec command
command.CommandText = "exec procedureName"
If your query location is in database itself.
I am struggling to make my dataGrid viev results of query. Connection with database is fine. Here is sample of my code:
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = "properConnectionString"
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * FROM WORKERS";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
using (OracleDataAdapter orclDataAdapter = new OracleDataAdapter(cmd))
{
DataTable dt = new DataTable();
orclDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Assuming that your call to the Oracle database is actually returning data, you're missing the databind statement on the gridview. Add this:
dataGridView1.DataBind();
place it right after the dataGridView1.DataSource = dt; line of code.
Most of my queries are very short, 1-3 records total. This is the code I have now. I am wondering if there is a way to capture userid directly from DataAdapter without going through a table. Thanks!
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable t = new DataTable();
dataAdapter.Fill(t);
int userid = 0;
if (t.Rows.Count > 0)
{
DataRow dr = t.Rows[0];
userid = dr.Field<int>(0);
If you have only one return value, you can use ExecuteScalar and you have ExecuteReader to get multiple return values.
Here's the msdn sample:
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Use a reader:
http://msdn.microsoft.com/en-US/library/system.data.sqlclient.sqldatareader(v=vs.80).aspx
Quicker and less resources 1 record or hundreds.
here is my code.
public DataSet ConnectandReadList()
{
DataSet ds = new DataSet();
string connection_string="Data Source=hermes;database=qcvalues; Integrated Security=SSPI;";
using (var myConnection = new SqlConnection(connection_string))
{
myConnection.Open();
var command = new SqlCommand(InitializeQuery(), myConnection);
var adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
}
return ds;
}
i then set the datasource this way:
dataGridView1.DataSource = ds.Tables[0];
the question is should i be returning a dataset or datatable? how would my code change if i were to be returning datatable?
I just return a DataTable when in your situation. And the more correct code is
using (var command = new SqlCommand(InitializeQuery(), myConnection))
using (var adapter = new SqlDataAdapter(command))
adapter.Fill(ds);
Change the word DataSet to DataTable and recompile. You will get an error where you consume this method's result, but you just need to change dataGridView1.DataSource = ds.Tables[0]; to dataGridView1.DataSource = ds;
Just replace all of your DataSet by DataTable (and for readability, all ds by resultTable) - or did I miss anything?
http://imar.spaanjaars.com/406/filling-a-datatable-or-dataset-the-quick-way
private DataTable GetDataTable()
{
string sql = "SELECT Id, Description FROM MyTable";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
{
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
DataTable myTable = new DataTable();
myTable.Load(myReader);
myConnection.Close();
return myTable;
}
}
}
}