I just ran Visual Studio's Code analysis, they told me to use a parameterized query for the following line of code:
using(var DA = new SQLiteDataAdapter(SQL, connectionstring))
The complete method:
public static DataTable SelectAll(string SQL)
{
//create a string(connectionstring), filled with the connectionstring
string connectionstring = "Data Source=" + LogicDatabase.Databasename + ";Version=3;Password=" + Settings.SQLiteDatabasePassword + ";";
//create a new DataSet
DataSet DS = new DataSet();
//Give name to a SQLiteDataAdapter
//Create a new SQLiteDataAdapter and fill it with the sql query, and path of the Database.
using(var DA = new SQLiteDataAdapter(SQL, connectionstring))
{
//Clear the dataset, so we are sure it is empty, before storing items in it.
DS.Clear();
//fill the dataset from the SQLiteDataAdapter.
DA.Fill(DS);
//Fill the DataTable with the first table of the DataSet
DataTable DT = DS.Tables[0];
//return the DataTable
return DT;
}
}
How can I implement parameters in this code?
Use the SQLiteCommand and fill it with your SQL statement. It has a property Parameters which you can fill with instances of SQLiteParameter. After that, you can use this command to create your SQLiteDataAdapter.
Related
I currently accessing a database using multiple queries and storing the results from the queries into DatatTables. I decided since I'm using multiple DataTables to store them inside a DataSet.
I can see that data is inside the DataTables when I print them out. However when I try to access them from the DataSet to print out the data, I get nothing back; it is empty.
string querytest1 = "SELECT * FROM test1";
string querytest2 = "SELECT * FROM test2";
string querytest3 = "SELECT * FROM test3";
using(OleDbConnection connection = new OleDbConnection(connectionString)){
OleDbCommand commandtest1 = new OleDbCommand(querytest1 , connection);
OleDbCommand commandtest2 = new OleDbCommand(querytest2 , connection);
OleDbCommand commandtest3 = new OleDbCommand(querytest3 , connection);
connection.Open();
DataSet dataSet = new DataSet();
OleDbDataAdapter dataAdaptertest1 = new OleDbDataAdapter(commandResults);
OleDbDataAdapter dataAdaptertest2 = new OleDbDataAdapter(commandResults);
OleDbDataAdapter dataAdaptertest3 = new OleDbDataAdapter(commandProjects);
DataTable dataTabletest1 = new DataTable();
DataTable dataTabletest2 = new DataTable();
DataTable dataTabletest3 = new DataTable();
dataAdaptertest1.Fill(dataTabletest1 );
dataAdaptertest2.Fill(dataTabletest2 );
dataAdaptertest3.Fill(dataTabletest3 );
dataTabletest1 = dataSet.Tables.Add("test1 ");
dataTabletest2 = dataSet.Tables.Add("test2 ");
dataTabletest3 = dataSet.Tables.Add("test3 ");
Console.WriteLine("DataSet has {0} DataTables \n", dataSet.Tables.Count);
foreach (DataTable objDt in dataSet.Tables)
Console.WriteLine("{0}", objDt.TableName);
return dataSet;
Expected behaviour: is to be able to access a DataTable from the DataSet and print out the data.
Example: Print out the contents in Test1
The code is redundant. I just don't know a better way to do this.
You don't need three adapters to fill a DataSet with the results from three commands.
You can simply write:
string query1 = "SELECT * FROM test1";
string query2 = "SELECT * FROM test2";
string query3 = "SELECT * FROM test3";
DataSet dataSet = new DataSet();
using(OleDbConnection connection = new OleDbConnection(connectionString)){
connection.Open();
OleDbCommand cmd = new OleDbCommand(q1, connection);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds, "Test1");
cmd.CommandText = q2;
da = new OleDbDataAdapter(cmd);
da.Fill(ds, "Test2");
cmd.CommandText = q3;
da = new OleDbDataAdapter(cmd);
da.Fill(ds, "Test3");
}
Console.WriteLine("DataSet has {0} DataTables \n", ds.Tables.Count);
foreach (DataTable objDt in ds.Tables)
Console.WriteLine("{0}", objDt.TableName);
The trick is filling the same DataSet three times instead of three different DataTables and giving at each fill a different name for each table created.
But, don't you see that dataSet.Tables.Add() call actually creates new DataTable instance, and trying to set its TableName property to "test1 " (btw. take care, space is not allowed in TableName).
That newly created instance(s) are set to properties dataTabletest1...3 - so, you lose access to the original ones, initially populated with data from the database.
You should do something like this:
DataTable dataTabletest1 = dataSet.Tables.Add("Test1");
DataTable dataTabletest2 = dataSet.Tables.Add("Test2");
DataTable dataTabletest3 = dataSet.Tables.Add("Test3");
dataAdaptertest1.Fill(dataTabletest1);
dataAdaptertest2.Fill(dataTabletest2);
dataAdaptertest3.Fill(dataTabletest3);
Please, check: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/adding-a-datatable-to-a-dataset
how can i refresh my datagridview here my code to view my data in datagridview but every time i enter new data i have to reopen my program to see the new data
using (IDbConnection dbconnection = new SQLiteConnection(conn))
{
dbconnection.Open();
SQLiteDataAdapter dataadapter = new SQLiteDataAdapter("SELECT * FROM tbl_Sample",conn);
DataSet ds = new System.Data.DataSet();
dataadapter.Fill(ds,"Info");
dataGridView1.DataSource = ds.Tables[0];
}
If you are using a DataSet or a DataTable as a datasource for the DataGridView, you can try something like this:
private void LoadDataToDgv()
{
using (IDbConnection dbconnection = new SQLiteConnection(conn))
{
dbconnection.Open();
SQLiteDataAdapter dataadapter = new SQLiteDataAdapter("SELECT * FROM tbl_Sample",conn);
DataSet ds = new System.Data.DataSet();
dataadapter.Fill(ds,"Info");
dataGridView1.DataSource = ds.Tables[0];
}
}
And then after you have added the new data to your tables, fetch the new dataset and reload the grid with the new rows:
//Code to add new data to Sql Table
LoadDataToDgv();
I would however recommend that you create a Class for the type of item you are binding to the grid (if you haven't created one yet) and the use BindingList to do the same. This question describes well how to use it for binding it as a source for DataGridViews.
i put the refresh function every time i put new data in the database so the datagridview will refresh every new data i enter
public void AddData()
{
using (IDbConnection dbconnection = new SQLiteConnection(conn))
{
dbconnection.Open();
using (IDbCommand dbCmd = dbconnection.CreateCommand())
{
string sqlQuery = "INSERT INTO tbl_sample (Name,Age) VALUES('" + textBox1.Text + "','" + textBox2.Text + "')"; ;
dbCmd.CommandText = sqlQuery;
using (IDataReader reader = dbCmd.ExecuteReader())
{
SQLiteDataAdapter dataadapter = new SQLiteDataAdapter("SELECT * FROM tbl_Sample", conn);
DataSet ds = new System.Data.DataSet();
dataadapter.Fill(ds, "Info");
dataGridView1.DataSource = ds.Tables[0];
dbconnection.Close();
}
}
}
}
I built a connection string to access data from a database to fill a datatable.
connectionname = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=d:\\projects\\checking.mdb; OLE DB Services=-1"
DataTable results = new DataTable();
using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
{
OleDbCommand cmd = new OleDbCommand("SELECT * from PatTestTable", thisConnection);
thisConnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
There is no error and in the debug mode, I can see the connection string being built correctly but the results datatable is empty. Did I miss any step?
I can use a query table:
var sheet = (_excel.ActiveSheet as Excel.Worksheet);
var rng = sheet.Range("A1");
var qt = sheet.QueryTables.Add("ODBC;...", rng, "SELECT * FROM myTable");
qt.Refresh();
and this will import the data correctly (e.g. dates actually display as dates etc...). But when I try and access the ListObject to apply a TableStyle I get an exception.
Now if I add a list object like:
var sheet = (_excel.ActiveSheet as Excel.Worksheet);
var qt = sheet.ListObjects.Add(
Excel.Enums.XlListObjectSourceType.xlSrcQuery,
"ODBC;...",
null,
Excel.Enums.XlYesNoGuess.xlNo,
rng,
"TableStyleMedium9").QueryTable;
qt.CommandType = Excel.Enums.XlCmdType.xlCmdSql;
qt.CommandText = "SELECT * FROM myTable";
qt.Refresh();
The the dates in the query display as decimal numbers and not dates...
I could just format the columns afterwards, but the problem is that I won't actually know the query that is being run as the user types this at runtime, so I would prefer to get Excel to do this.
So essentially, what I want, is to use the first bit of code and apply a TableStyle to it.
Can anyone help?
This doesn't do coloring, but it does organize the data into a datatable, and when you're debugging with breakpoints and mouse over the datatable after its been filled you can see all the data organized into columns. What you can then do with the datatable is bind it to a datagrid view on your win forms element.
I have this DataTable DataTable = new DataTable(); as a global field at the top.
OleDbConnection conn = new OleDbConnection();
//This is making a connection to the excel file, don't worry about this I think you did it differently.
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + stringFileName + ";" + "Extended Properties=\"Excel 12.0;HDR=Yes;\""; OleDbCommand cmd = new OleDbCommand
("SELECT * FROM [" + sheetFromTo + "]", conn);
DataSet dataSet1 = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmd);
try
{
conn.Open();//opens connection
dataSet1.Clear();//empties, incase they refill it later
dataAdapter.SelectCommand = cmd;//calls the cmd up above
dataAdapter.Fill(dataSet1);//fills the dataset
dataGridView1.DataSource = dataSet1.Tables[0];//puts the dataset in the dataGridview
//important** creates a datatable from the dataset, most of our work with the server is with this datatable
DataTable dataTable = dataSet1.Tables[0];
DataTable = dataTable;
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
hi guys I'm trying to save data to database through datagridview with a button but I get the following error every time I run the application and here's my code:
DataTable Table = new DataTable();
BindingSource bindingSource1 = new BindingSource();
string connetionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Database/Database.accdb;";
string sql = "SELECT * FROM IAE;";
OleDbConnection connection = new OleDbConnection(connetionString);
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadapter);
DataSet ds = new DataSet();
connection.Open();
dataGridView1.DataSource = ds.Tables["IAE"];
dataadapter.Update((DataTable)bindingSource1.DataSource);
connection.Close();
the error : Value Cannot be null. Parameter name: dataTable
need your help and thanks
Reason of error is your bindingSource1.DataSource property is NULL. Your are not assigning any DATASOURCE to your bindingsource class