read data from sqlite into C# then to sqlite - c#

Reproducible Example:
sqlite db test3.s3db has one table with name "MathRec":
name score
Bill 2
Mary 3
John 3
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SQLite;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string fullPath = "C:\\Users\\Desktop\\dataset\\test3.s3db";
SQLiteConnection conread = new SQLiteConnection("Data Source=" + fullPath);
conread.Open();
string selectSQL = "SELECT * FROM MathRec";
SQLiteCommand selectCommand = new SQLiteCommand(selectSQL, conread);
SQLiteDataReader dataReader = selectCommand.ExecuteReader();
DataSet ds = new DataSet();
DataTable dt = new DataTable("MathRec");
dt.Load(dataReader);
ds.Tables.Add(dt);
// Create a table in the database to receive the information from the DataSet
string fullPath2 = "C:\\Users\\\\Desktop\\dataset\\test4.s3db";
SQLiteConnection conwrite = new SQLiteConnection("Data Source=" + fullPath2);
conwrite.Open();
SQLiteCommand cmd = new SQLiteCommand(conwrite);
cmd.CommandText = "DROP TABLE IF EXISTS MathRec";
cmd.ExecuteNonQuery();
cmd.CommandText = "CREATE TABLE MathRec(name text , score integer)";
cmd.ExecuteNonQuery();
SQLiteDataAdapter adaptor = new SQLiteDataAdapter("SELECT * from MathRec", conwrite);
adaptor.InsertCommand = new SQLiteCommand("INSERT INTO MathRec VALUES(:name, :score)", conwrite);
adaptor.InsertCommand.Parameters.Add("name", DbType.String, 0, "name");
adaptor.InsertCommand.Parameters.Add("score", DbType.Int32, 0, "score");
adaptor.Update(ds, "MathRec");
}
}
}
Questions:
Table MathRec is created in test4.s3db with column names: name and socre, but the table is empty with no records inserted.
Help is needed!
Please don't ask me why I am just copying one db to another, because I am testing one part of the code for a bigger project, where I will do calculations to the Dataset in the middle step in the future.
Thanks!
To simplify the question:
This works (use datatable and adapter to update the original sqlite table):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string fullPath = "C:\\Users\\data\\test.db";
SQLiteConnection conread = new SQLiteConnection("Data Source=" + fullPath);
conread.Open();
SQLiteDataAdapter DB = new SQLiteDataAdapter("SELECT speed, dist FROM Cars2", conread);
DataSet DS = new DataSet();
DB.Fill(DS, "NewCars");
object[] rowVals = new object[2];
rowVals[0] = 10;
rowVals[1] = 20;
DS.Tables["NewCars"].Rows.Add(rowVals);
DB.InsertCommand = new SQLiteCommand("INSERT INTO Cars2 (speed, dist)
" + " VALUES (:speed, :dist)", conread);
DB.InsertCommand.Parameters.Add("speed", DbType.Double, 0, "speed");
DB.InsertCommand.Parameters.Add("dist", DbType.Double, 20, "dist");
DB.Update(DS, "NewCars");
}
}
}
And this works (create a new sqlite table from old one):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string fullPath = "C:\\Users\\data\\test.db";
SQLiteConnection conread = new SQLiteConnection("Data Source=" + fullPath);
conread.Open();
SQLiteCommand cmd = new SQLiteCommand(conread);
cmd.CommandText = "DROP TABLE IF EXISTS Cars";
cmd.ExecuteNonQuery();
cmd.CommandText = "CREATE TABLE Cars (speed REAL , dist REAL)";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO Cars SELECT * from DS";
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
}
But this one is what I wanted (use datatable and adapter to create new table in sqlite) and is not working:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string fullPath = "C:\\Users\\data\\test.db";
SQLiteConnection conread = new SQLiteConnection("Data Source=" + fullPath);
conread.Open();
SQLiteDataAdapter DB = new SQLiteDataAdapter("SELECT speed, dist FROM Cars2", conread);
DataSet DS = new DataSet();
DB.Fill(DS, "NewCars");
object[] rowVals = new object[2];
rowVals[0] = 10;
rowVals[1] = 20;
DS.Tables["NewCars"].Rows.Add(rowVals);
SQLiteDataAdapter DB2 = new SQLiteDataAdapter("SELECT speed, dist FROM Cars3", conread);
DB2.InsertCommand = new SQLiteCommand("INSERT INTO Cars3 (speed, dist)
" + " VALUES (:speed, :dist)", conread);
DB2.InsertCommand.Parameters.Add("speed", DbType.Double, 0, "speed");
DB2.InsertCommand.Parameters.Add("dist", DbType.Double, 20, "dist");
DB2.Update(DS, "NewCars");
}
}
}
Please help!!!

I found the answer!
Adapter.Update can only be used to update the original table in the database and not to save the datatable in a new one. Please refer to the thread for answers:
C# Dataset to Access DB
Cheers!

The easiest way to copy one table to another database is to attach the second database to the first connection, and copy the data directly:
ATTACH '...\test4.s3db' AS 'test4';
DROP TABLE IF EXISTS test4.MathRec;
CREATE TABLE test4.MathRec(name text , score integer);
INSERT INTO test4.MathRec SELECT * FROM MathRec;
If you want to do calculations, you might be able to do them in SQL, in the SELECT statement.
If not, you have to read the data with a SELECT and then execute one INSERT statement for each record to be written. (In that case, you don't need the ATTACH.)

Related

Is it possible to get the length of the SQL column through SqlDataReader?

Using SqlDataReader, I am able to get both the column name and SQL datatype, but I can't seem to find a way to get length, precision, or scale. Is there another way I can get this data for each column?
code:
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
public class StoredProcedures
{
[SqlProcedure]
public static void CLRExec(SqlString query)
{
SqlContext.Pipe.Send(DateTime.Now.ToString() + " -- " + query.ToString());
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
string sQuery = query.ToString();
// Create the record and specify the metadata for the columns.
SqlDataRecord record = new SqlDataRecord(
new SqlMetaData("col1", SqlDbType.NVarChar, 100),
new SqlMetaData("col2", SqlDbType.NVarChar, 100));
connection.Open();
SqlCommand command = new SqlCommand(sQuery, connection);
SqlDataReader reader = command.ExecuteReader();
//DataTable table = reader.GetSchemaTable();
// Mark the begining of the result-set.
SqlContext.Pipe.SendResultsStart(record);
for (int i = 0; i < reader.FieldCount; i++)
{
record.SetString(0, reader.GetName(i).ToString());
record.SetString(1, reader.GetDataTypeName(i).ToString());
// Send the row back to the client.
SqlContext.Pipe.SendResultsRow(record);
}
SqlContext.Pipe.SendResultsEnd();
}
}
}

How to use DataTable from SQL Server in C#

I want to view this table in the list box in C#
enter image description here
I'm using this query to show the table
select
Chicken_Name, WithOrWithout_Name, Chicken_Price
from
Tbl_Add a
full outer join
tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID
full outer join
Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ;
And this code to put it in the list box in C#
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lst_SHowdata.ValueMember = "Chicken_ID";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
This is the full code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace HABIBIS_GRILL
{
public partial class HabibisGrll : Form
{
SqlConnection connection;
string connectionString;
public HabibisGrll()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["HABIBIS_GRILL.Properties.Settings.HabibisGrilllDataBAseConnectionString"].ConnectionString;
}
private void Form1_Load(object sender, EventArgs e)
{
Chicken();
}
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lst_SHowdata.ValueMember = "Chicken_ID";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
}
}
}
}
The problem is I need to use one list box for each column, how to make them in one list box or do I use another tool ?
And how to put 2 or more tables in one datatable (adapter) ?
Thank you ^^"
first question:
you can use gridview for your query if you want to show more than 1 column from your query.
Second question:
and you can use DataSet to get more than 1 table in case you need.
check this:
string queryCustomer =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryCustomer , connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet , "Customers");
string queryOrders =
"SELECT OrderId, Date FROM dbo.Orders";
SqlDataAdapter adapterOrder = new SqlDataAdapter(queryOrders , connection);
adapterOrder.Fill(dataSet , "Orders");
//assume you have a GridView named myGridview.
//than set its DataSource to one of your DataSet tables.
myGridview.DataSource = dataSet.Tables[0] //customers will be the source

compare the length of two variable

I am a beginner programmer.
I wrote following code and I want to compare the lenght of the Track ID (which is in my data set) with the Track ID (which is extracted from the web page) which both are highlighted.(my data set has two fields(user id-track id), i want to compare this track id with the track id which is return from web page)
I want to to it like:
if (client.Contains(Convert.ToString(TrackID))&&row["TrackID"].lenght=Track ID.lenght)
Thank you
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden.accdb";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the UserID
adapter.Fill(dt);
int UserID=0,TrackID=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == (Convert.ToString(TrackID).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average" + counter);
}
conn.Close();
}
}
}
Why not do this?
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == Convert.ToString(TrackID).ToLower())
{
counter++;
}

Error in adapter.fill function

I am a beginner programmer.
I wrote the following code that shows an error in "adapter.fill(dt) ??????
this code must do the following steps:
1-connect to my dataset that has two fields :UserID,TrackID (2916 fields) 2-Read the dataset line by line and put the UserId of each recored to a url(instead of ). 3-Search through the webpage 4-if it finds the TrackId (exactly the same) which is related to UserId, add 1 to counter.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden.accdb";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the UserID
adapter.Fill(dt);
int UserID=0,TrackID=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == (Convert.ToString(TrackID).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average" + counter);
}
conn.Close();
}
}
}
This is invalid:
"Select * from hidden.accdb"
hidden.accdb should be table name that contains the UserID and TrackID columns. not access database file name

Export multiple tables from SQL Server to XML for restore

I have a web application in C# / ASP.NET. I want to export all the database table's data, with the same unique key (Company ID). All the tables have this key (different for every company). I want to do that for future backup. Is it possible with Linq or classic C#? How can achieve this backup and restore?
One of the example to the solution is
using System.Data.SqlClient;
using System.Data;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var connStr = "Data Source=MOHSINWIN8PRO\\SQLEXPRESS;Initial Catalog=AB2EDEMO;Integrated Security=True";
var xmlFileData = "";
DataSet ds = new DataSet();
var tables = new[] {"Hospital", "Patient"};
foreach (var table in tables)
{
var query = "SELECT * FROM "+ table +" WHERE (Hospital_Code = 'Hosp1')";
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
conn.Dispose();
xmlFileData+=ds.GetXml();
}
File.WriteAllText("D://SelectiveDatabaseBackup.xml",xmlFileData);
}
}
}
this will create SelectiveDatabaseBackup.xml which can be later used to restore the backup
SaveFileDialog SD = new SaveFileDialog();
if (SD.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
{
System.IO.StreamWriter SW = new System.IO.StreamWriter(SD.FileName);
foreach (string str in checkedListBox1.CheckedItems)
{
string XMLSTR = //Heads.funtions.ConvertDatatableToXML(
Heads.funtions.fire_qry_for_string(string.Format("Select * from {0} FOR XML AUTO,TYPE, ELEMENTS ,ROOT('{0}')", str)); // , str);
SW.Write(XMLSTR);
SW.WriteLine("###TABLEEND###");
}
SW.Close();
//_CommonClasses._Cls_Alerts.ShowAlert("Clean Up Completed...!!!", "CleanUP", MessageBoxIcon.Information);
}

Categories