Today I tried to use SQLite database with my small WPF application, but I keep getting XamlParseException was unhandled. By taking out lines of code, I managed to notice that cmd.ExecuteNonQuery();causes the exception. In the rest, the SQLite connection seems working and also creating the database file.
public MainWindow()
{
InitializeComponent();
SQLiteConnection conn = new SQLiteConnection(#"Data Source=C:\Users\Vitas\Desktop\TimeCounter.sqlite");
conn.Open();
string commandText = "CREATE TABLE [EmpInfo]";
SQLiteCommand cmd = new SQLiteCommand(commandText, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
You need a definition of fields when creating the table. Example:
string commandText = "CREATE TABLE [EmpInfo] (EmpId int)";
Ref: Create table syntax
Related
i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}
I am trying to create an sqlite db programmatically if it doesn't exist. I have written the following code but I am getting an exception at the last line.
if (!System.IO.File.Exists("C:\\Users\\abc\\Desktop\\1\\synccc.sqlite"))
{
Console.WriteLine("Just entered to create Sync DB");
SQLiteConnection.CreateFile("C:\\Users\\abc\\Desktop\\1\\synccc.sqlite");
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
command.ExecuteNonQuery();
}
sqlite2 = new SQLiteConnection("Data Source=C:\\Users\\abc\\Desktop\\1\\synccc.sqlite");
I get the exception at the line command.ExecuteNonQuery(); The exception is Invalid operation exception was unhandled. Is there any other way to add an sqlite file to your project? Can I do it manually? If not then how can I solve the above issue?
To execute any kind of data definition command on the database you need an open connection to pass the command. In your code you create the connection AFTER the execution of the query.
Of course, after that creation, you need to open the connection
if (!System.IO.File.Exists(#"C:\Users\abc\Desktop\1\synccc.sqlite"))
{
Console.WriteLine("Just entered to create Sync DB");
SQLiteConnection.CreateFile(#"C:\Users\abc\Desktop\1\synccc.sqlite");
using(var sqlite2 = new SQLiteConnection(#"Data Source=C:\Users\abc\Desktop\1\synccc.sqlite"))
{
sqlite2.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
command.ExecuteNonQuery();
}
}
However, if you use the version 3 of the provider, you don't have to check for the existence of the file. Just opening the connection will create the file if it doesn't exists.
I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)
This is my code for inserting into database from textfields.
SqlConnection Connection = new SqlConnection("Data Source=ESHA\\SQLEXPRESS;Initial Catalog=Gen_Lic;User ID=sa;Password=sa#");
SqlCommand Command = Connection.CreateCommand();
try
{
// Open Connection
Connection.Open();
////Console.WriteLine("Connection Opened");
// Create INSERT statement with named parameters
Command.CommandText = "INSERT INTO Gen_Lic(Lic_No, UserID, Org, UserName, SolType, Version, Lic_Type, Meap_Supp, Lic_From, Lic_To, Supp_From, Supp_To, Max_User, Max_Mach, Mach_IP, Mach_MAC) VALUES (#Lic_No, #UserID, #Org, #UserName, #SolType, #Version, #Lic_Type, #Meap_Supp, #Lic_From, #Lic_To, #Supp_From, #Supp_To, #Max_User, #Max_Mach, #Mach_IP, #Mach_MAC)";
// Add Parameters to Command Parameters collection
Command.Parameters.AddWithValue("#Lic_No", txtLNo.Text);
Command.Parameters.AddWithValue("#UserID", txtUID.Text);
Command.Parameters.AddWithValue("#Org", txtOrg.Text);
Command.Parameters.AddWithValue("#UserName", txtUName.Text);
Command.Parameters.AddWithValue("#SolType", txtSType.Text);
Command.Parameters.AddWithValue("#Version", txtVer.Text);
Command.Parameters.AddWithValue("#Lic_Type", drpLType.SelectedItem.Text);
Command.Parameters.AddWithValue("#Meap_Supp", rdoMeapSupport.SelectedValue.ToString());
Command.Parameters.AddWithValue("#Lic_From", lblLFrom.Text);
Command.Parameters.AddWithValue("#Lic_To", lblLTo.Text);
Command.Parameters.AddWithValue("#Supp_From", lblSuppFrom.Text);
Command.Parameters.AddWithValue("#Supp_To", lblSuppTo.Text);
Command.Parameters.AddWithValue("#Max_User", txtMaxUsr.Text);
Command.Parameters.AddWithValue("#Max_Mach", txtMaxMach.Text);
Command.Parameters.AddWithValue("#Mach_IP", txtMachIP.Text);
Command.Parameters.AddWithValue("#Mach_MAC", txtMachMac.Text);
Connection.Close();
}
Now the problem is the code is working fine, but the values are not getting inserted into the database. Also, when I apply a breakpoint at the starting of the connection formation, a new blank IE window opens up.
Can someone guide me where am I going wrong?
I think, you are missing the following:
Command.ExecuteNonQuery();
before the Connection.Close()
Please run this query again the database
Command.ExecuteNonQuery();
before closing the connection
I am trying to get column information in C# from a SQL table on SQL Server. I am following the example in this link: http://support.microsoft.com/kb/310107 My program strangely gets hung up when it tries to close the connection. If the connection is not closed, the program exits without any Exceptions. Here's my code:
SqlConnection connection = new SqlConnection(#"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
Putting the SqlConnection inside a using block also causes the application to hang unless CommandBehavior.KeyInfo is changed to CommandBehavior.SchemaOnly.
using (SqlConnection connection = new SqlConnection(#"MyConnectionString"))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast even here in the using
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
}
The table in question has over 3 million rows, but since I am only obtaining the Schema information, I would think this wouldn't be an issue. My question is: Why does my application get stuck while trying to close a connection?
SOLUTION: Maybe this isn't optimal, but it does work; I inserted a command.Cancel(); statement right before Close is called on connection:
SqlConnection connection = new SqlConnection(#"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
command.Cancel(); // <-- This is it.
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
I saw something like this, long ago. For me, it was because I did something like:
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader();
// here, I started looping, reading one record at a time
// and after reading, say, 100 records, I'd break out of the loop
connection.Close(); // this would hang
The problem is that the command appears to want to complete. That is, go through the entire result set. And my result set had millions of records. It would finish ... eventually.
I solved the problem by adding a call to command.Cancel() before calling connection.Close().
See http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=610 for more information.
It looks right to me overall and I think you need a little optimization. In addition to the above suggestion regarding avoiding DataReader, I will recommend to use connection pooling. You can get the details from here :
http://www.techrepublic.com/article/take-advantage-of-adonet-connection-pooling/6107854
Could you try this?
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = new SqlCommand("SET FMTONLY ON; " + yourQueryString + "; SET FMTONLY OFF;",conn);
conn.Open();
dt.Load(cmd.ExecuteReader());
}
SET FMTONLY ON/OFF from MSDN seems the way to go
There is an specific way to do this, using SMO (SQL Server management objects)
You can get the collection of tables in the database, and then read the properties of the table you're interested in (columns, keys, and all imaginable properties)
This is what SSMS uses to get and set properties of all database objects.
Look at this references:
Database.Tables Property
Table class
This is a full example of how to get table properties:
Retrieving SQL Server 2005 Database Info Using SMO: Database Info, Table Info
This will allow you to get all the possible information from the database in a very easy way. there are plenty of samples in VB.NET and C#.
I would try something like this. This ensures all items are cleaned up - and avoids using DataReader. You don't need this unless you have unusually large amounts of data that would cause memory issues.
public void DoWork(string connectionstring)
{
DataTable dt = new DataTable("MyData");
using (var connection = new SqlConnection(connectionstring))
{
connection.Open();
string commandtext = "SELECT * FROM MyTable";
using(var adapter = new SqlDataAdapter(commandtext, connection))
{
adapter.Fill(dt);
}
connection.Close();
}
Console.WriteLine(dt.Rows.Count);
}