how to create sqlite database in wpf? - wpf

I am new to windows desktop application development.Will you please suggest me how to create a SQLite database in windows presentation foundation(wpf)?

You need to do 2 things:
Add the SQLite dll to your application references
Write a class that builds the Db.
for example:
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Database
{
public class DbCreator
{
SQLiteConnection dbConnection;
SQLiteCommand command;
string sqlCommand;
string dbPath = System.Environment.CurrentDirectory + "\\DB";
string dbFilePath;
public void createDbFile()
{
if (!string.IsNullOrEmpty(dbPath) && !Directory.Exists(dbPath))
Directory.CreateDirectory(dbPath);
dbFilePath = dbPath + "\\yourDb.db";
if (!System.IO.File.Exists(dbFilePath))
{
SQLiteConnection.CreateFile(dbFilePath);
}
}
public string createDbConnection()
{
string strCon = string.Format("Data Source={0};", dbFilePath);
dbConnection = new SQLiteConnection(strCon);
dbConnection.Open();
command = dbConnection.CreateCommand();
return strCon;
}
public void createTables()
{
if (!checkIfExist("MY_TABLE"))
{
sqlCommand = "CREATE TABLE MY_TBALE(idnt_test INTEGER PRIMARY KEY AUTOINCREMENT,code_test_type INTEGER";
executeQuery(sqlCommand);
}
}
public bool checkIfExist(string tableName)
{
command.CommandText = "SELECT name FROM sqlite_master WHERE name='" + tableName + "'";
var result = command.ExecuteScalar();
return result != null && result.ToString() == tableName ? true : false;
}
public void executeQuery(string sqlCommand)
{
SQLiteCommand triggerCommand = dbConnection.CreateCommand();
triggerCommand.CommandText = sqlCommand;
triggerCommand.ExecuteNonQuery();
}
public bool checkIfTableContainsData(string tableName)
{
command.CommandText = "SELECT count(*) FROM " + tableName;
var result = command.ExecuteScalar();
return Convert.ToInt32(result) > 0 ? true : false;
}
public void fillTable()
{
if (!checkIfTableContainsData("MY_TABLE"))
{
sqlCommand = "insert into MY_TABLE (code_test_type) values (999)";
executeQuery(sqlCommand);
}
}
}
}
Good luck!

1.using System.Data;
2.using System.Data.SQLite;
DataTable tb = new DataTable();
string connection = #"Data Source=C:\Folder\SampleDB.db;Version=3;New=False;Compress=True;";
SQLiteConnection sqlite_conn = new SQLiteConnection(connection);
string stringQuery = "Select * from Student";
sqlite_conn.Open();
var SqliteCmd = new SQLiteCommand();
SqliteCmd = sqlite_conn.CreateCommand();
SqliteCmd.CommandText = stringQuery;
SQLiteDataAdapter da = new SQLiteDataAdapter(SqliteCmd);
DataSet ds = new DataSet();
da.Fill(tb);

Related

Convert SqlDataReader to object for .NET Framework 4

I am working on a class Library with .NET Framework 4.0. I have managed to pull a row using ADO.NET, but I'm unable to read individual values. I want the end result in class object. I have tried reading individual value dbReader.GetValue(dbReader.GetOrdinal("BranchCode")) but getting empty result.
Branch class:
public class Branch
{
public Branch() { }
public int BranchId { get; set; }
public string BranchCode { get; set; }
public string BranchName { get; set; }
}
DataReader class:
public void Initialize()
{
try
{
string connectionString = "xyz";
SqlConnection dbConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from dbo.Branch", dbConnection);
dbConnection.Open();
SqlDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
var x1 = dbReader.GetValue(dbReader.GetOrdinal("BranchId"));
var x2 = dbReader.GetValue(dbReader.GetOrdinal("BranchCode"));
var x3 = dbReader.GetValue(dbReader.GetOrdinal("BranchName"));
}
var dd = "Dd";
}
catch(Exception ex)
{
throw ex;
}
}
You have a number of issues with your code.
You need to actually create the Branch objects and do something with them. For example, return List.
To read the values, the easiest way is to do (typeNameHere) dbReader["ColumnName"]
You should SELECT exactly the right columns not SELECT *
Don't catch then re-throw exceptions with throw ex; as it wipes the stakc trace.
public List<Branch> Initialize()
{
string connectionString = "xyz";
const string query = #"
Select
b.BranchId,
b.BranchCode,
b.BranchName
from dbo.Branch b;
";
using (SqlConnection dbConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, dbConnection))
{
dbConnection.Open();
using (SqlDataReader dbReader = cmd.ExecuteReader())
{
var list = new List<Branch>();
while (dbReader.Read())
{
var b = new Branch();
b.BranchId = (int)dbReader["BranchId"];
b.BranchCode = (string)dbReader["BranchCode"];
b.BranchName = (string)dbReader["BranchName"];
list.Add(b);
}
return list;
}
}
}

Save excel file in database using c#

I have an excel file. Now I need to save data of excel file in database. What is the simplest way to do that using c# with simple example? Thank in advance
This will do what you want.
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\your_path\\Import_List.xls;Extended Properties=Excel 8.0;");
ExcelConnection.Open();
string expr = "SELECT * FROM [Sheet1$]";
OleDbCommand objCmdSelect = new OleDbCommand(expr, ExcelConnection);
OleDbDataReader objDR = null;
SqlConnection SQLconn = new SqlConnection();
string ConnString = "Data Source=Your_Database_Name;Initial Catalog=Table_Name;Trusted_Connection=True;";
SQLconn.ConnectionString = ConnString;
SQLconn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLconn))
{
bulkCopy.DestinationTableName = "tblTest";
try
{
objDR = objCmdSelect.ExecuteReader();
bulkCopy.WriteToServer(objDR);
ExcelConnection.Close();
//objDR.Close()
SQLconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
To copy from a SQL Server table to an Excel file, try the following.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
Or, with a 'Where' clause, you can have more control of the output.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Update [Sheet1$] set name = 'New Name' where id=1";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to import Excel file data into database?

I've created a form where the manager can import an Excel file to DataGridView but I'm having trouble saving it to the database.
Reason: So when the manager imports the rota Excel file to DataGridView I want the other users to see it in a different form.
My form 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.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace Login
{
public partial class EmployeeRota : Form
{
string con = "Data Source=dqq5ndqef2.database.windows.net;Initial Catalog=Login;Integrated Security=False;User ID=richardjacobs97;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public EmployeeRota()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
string PathCpnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathCpnn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
myDataAdapter.Update(dt);
}
private void EmployeeRota_Load(object sender, EventArgs e)
{
string connectionString = con;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Rota (Id, Name, Date) Values (#Id, #Name, #Date)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
int i = 0;
i = dataGridView1.RowCount - 1;
cmd.Parameters.AddWithValue("#Id", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Date", dataGridView1.Rows[i].Cells[0].Value);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
}
}
}
}
Database: Database pic
Form: Form pic
Any suggestions why I get this error?
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
You are receiving that error because the Load function runs when the page is first opened. You should move this into a separate functions so that it can be called at select times, maybe from a button click. This is prior to any data source being applied to the
DataGridView. You need to add the following to make sure there are rows in the table.
i = dataGridView1.RowCount - 1;
if(i<0) // Meaning that the row count was 0
{
return;
}
cmd.Parameters.AddWithValue("#Id", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Date", dataGridView1.Rows[i].Cells[0].Value);

Is there a utility to dump an existing log4j log file into a relational database?

Seems, like a very basic thing, but I could not find it.
I have a bunch of log4j/log4net log files. I would like to dump them into a database in order to be able to analyze them with ease.
I thought I would find a tool to do it in no time, apparently I am wrong.
Does anyone know of such a tool?
OK, so I found no utility. Had to write my own. Of course, it is strictly tailored to my immediate needs (time is money), however, it can save you a bit of time to start your own, in case of a need. Here is the complete code in C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
public class LogEntry
{
private const string PATTERN = #"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{4}) (\S+) \[(\d+)\] (\w+) (\S+) - (.*)$";
private static readonly Regex s_regex = new Regex(PATTERN, RegexOptions.Compiled);
public DateTime TS;
public string Machine;
public int Thread;
public string Level;
public string Logger;
public string Message;
public static LogEntry TryCreate(string line)
{
var match = s_regex.Match(line);
return match.Success ? new LogEntry
{
TS = DateTime.ParseExact(match.Groups[1].Value, "yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture),
Machine = match.Groups[2].Value,
Thread = int.Parse(match.Groups[3].Value),
Level = match.Groups[4].Value,
Logger = match.Groups[5].Value,
Message = match.Groups[6].Value,
} : null;
}
public void AppendToMessage(string line)
{
Message += Environment.NewLine + line;
}
}
static void Main()
{
const string SQL = #"
INSERT INTO log ( ts, machine, thread, level, logger, message, journalId)
VALUES (#ts, #machine, #thread, #level, #logger, #message, #journalId)
";
using (var connection = new SqlConnection("server=localhost;database=misc;uid=SantaClaus;pwd=MerryChristmas"))
{
connection.Open();
using (var command = new SqlCommand(SQL, connection))
{
var tsParam = new SqlParameter("#ts", SqlDbType.DateTime);
var machineParam = new SqlParameter("#machine", SqlDbType.NVarChar, 32);
var threadParam = new SqlParameter("#thread", SqlDbType.Int);
var levelParam = new SqlParameter("#level", SqlDbType.NVarChar, 10);
var loggerParam = new SqlParameter("#logger", SqlDbType.NVarChar, 128);
var messageParam = new SqlParameter("#message", SqlDbType.NVarChar, -1);
var journalIdParam = new SqlParameter("#journalId", SqlDbType.Int);
command.Parameters.Add(tsParam);
command.Parameters.Add(machineParam);
command.Parameters.Add(threadParam);
command.Parameters.Add(levelParam);
command.Parameters.Add(loggerParam);
command.Parameters.Add(messageParam);
command.Parameters.Add(journalIdParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
int i = 0;
foreach (var file in Directory.GetFiles(#"c:\tmp\dfbje01"))
{
journalIdParam.Value = OpenJournal(connection, file);
command.Transaction = connection.BeginTransaction();
foreach (var e in GetLogEntries(file))
{
tsParam.Value = e.TS;
machineParam.Value = e.Machine;
threadParam.Value = e.Thread;
levelParam.Value = e.Level;
loggerParam.Value = e.Logger;
messageParam.Value = e.Message;
command.ExecuteNonQuery();
++i;
if (i == 1000)
{
i = 0;
command.Transaction.Commit();
command.Transaction = connection.BeginTransaction();
}
}
command.Transaction.Commit();
CloseJournal(connection, journalIdParam.Value);
}
}
}
}
private static void CloseJournal(SqlConnection connection, object id)
{
const string SQL = "UPDATE journal SET done = 1 WHERE id = #id";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#id", id));
command.ExecuteNonQuery();
}
}
private static object OpenJournal(SqlConnection connection, string filePath)
{
const string SQL = "INSERT INTO journal (filePath) OUTPUT inserted.id VALUES (#filePath)";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#filePath", filePath));
return command.ExecuteScalar();
}
}
private static IEnumerable<LogEntry> GetLogEntries(string filePath)
{
LogEntry prev = null;
foreach (var line in File.ReadLines(filePath))
{
var logEntry = LogEntry.TryCreate(line);
if (logEntry != null)
{
if (prev != null)
{
yield return prev;
}
prev = logEntry;
}
else if (prev != null)
{
prev.AppendToMessage(line);
}
else
{
// Oops
Console.WriteLine(line);
}
}
if (prev != null)
{
yield return prev;
}
}
}
}
Mind trying out the filtering, search, colorizing features of the latest developer snapshot of Chainsaw? It has a good number of features which may avoid the need to use a DB. If you use a VFSLogFilePatternReceiver, it can parse and tail any regular text file, including those created by log4net.
Latest developer snapshot of Chainsaw is available here:
http://people.apache.org/~sdeboy

CRUD operation in MVC with out Entity framework

Hi I am beginner in MVC , I am trying to achieve CRUD operation in MVC using SQL with out Entity Framework or LINQ-SQL class. I done well with insert and getting the details of the selected table but when coming to Edit, details and delete I am confused how to perform so can some one help me out.
This is my code
Create a new Employee
public ActionResult Index(Test test)
{
try
{
if (ModelState.IsValid)
{
test.insert(test);
test.Name = "";
test.LastName = "";
}
}
catch (Exception)
{
}
return View(test);
}
Display all results
public ActionResult display()
{
Test tst = new Test();
return View(tst.getList());
}
This is my code in class file
public class Test
{
public int EmpID { get; set; }
[Required]
[DisplayName("Name")]
public string Name { get; set; }
[Required]
[DisplayName("LastName")]
public string LastName { get; set; }
string strConnection = ConfigurationManager.ConnectionStrings["SomeDataBase"].ConnectionString.ToString();
public void insert(Test test)
{
using (SqlConnection con = new SqlConnection(strConnection))
{
SqlCommand cmd = new SqlCommand("insert into Employee values('" + test.Name + "','" + test.LastName + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
public List<Test> getList()
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
public List<Test> edit(int id)
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
}
Can some one help me how to do the remaining operations like Details, Edit update and Delete.
for Details you can use
public Test details(int id)
{
Test _products = new Test();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
_products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_products.Name = dr["FirstName"].ToString();
_products.LastName = dr["LastName"].ToString();
}
catch(exception ex)
{
/* Do Some Stuff */
}
return _products;
}
And from your Controller
public ActionResult Details(int id)
{
Test tst = new Test();
return tst.Details(id);
}
for Edit you can use
public Bool Edit(test tst)
{
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("UPDATE TABLE Employee SET FirstName='"+tst.Name+"',Lastname='"+tst.LastName+"' where EmpID='" + tst.EmpId + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
return true;
}
catch(exception ex)
{
/* Do Some Stuff */
}
}
And from your Controller
public ActionResult Edit(test tsts)
{
Test tst = new Test();
return tst.Edit(tsts);
}
and proceed similarly for the rest of the cases

Resources