I would like some help with my Visual Studio C# code with inserting unicode strings into a SQLite database.
Below is my test code to write a test string to the database:
string testStr = "á Á ñ ç é á";
SQLiteConnection mydataConnection = new SQLiteConnection(); // setup new sql connection obj
try
{
//// SQLite DB
mydataConnection.ConnectionString =
"Data Source=C:\\Users\\John\\Desktop\\location.db; Version=3; UseUTF16Encoding=True;Synchronous=Normal;New=False"; // set up the connection string
mydataConnection.Open(); // open the connection to the db
SQLiteCommand myCmd = new SQLiteCommand(); // create a new command object
myCmd.Connection = mydataConnection; // whats its connected to, see above connection string
SQLiteParameterCollection myParameters = myCmd.Parameters; // good pratice to use parameters to pass data to db
myParameters.AddWithValue("#name", testStr); //
myCmd.CommandText = "INSERT INTO location (name) VALUES (#name)";
myCmd.ExecuteNonQuery();
}
catch (SQLiteException d)
{
string myerror = "Database Error" + d;
MessageBox.Show(myerror);
}
finally // good pratice to close db connection in a finally so exceptions dont leave open.
{
mydataConnection.Close();
}
When I view the database/table (using SQLite Administrator) the string looks like this:
á à ñ ç é á
As a test, I can copy & paste the string direct into the database using SQLite Administrator and the string is saved and can subsequently be viewed OK.
I have tried toggling "UseUTF16Encoding=True;" True / False - no difference.
Any ideas what I'm doing wrong.
This problem turned out to be an issue with the SQLite Administrator app I was using to view/check the db/data. Seems it was this app that would not display the characters correctly when inserted by my code. Strangely though if you used the SQLite Administrator app to add the test text directly (by copy & pasting the test string into the table/field) it would display, save & subsequently view OK. Anyway now using SourceForge SQLite Database Browser to check my code writes correctly and all seems in order.
Many thanks for anyone who took the time to comment, hope this is of help to someone else.
You can try with this code
byte[] encod = Encoding.Default.GetBytes(testStr );
string result = Encoding.UTF8.GetString(encod);
myParameters.AddWithValue("#name", result);
Related
I wrote the following code for connecting to an oracle database with my c# code:
private string GenerateConnectionString()
{
return "Data Source=( DESCRIPTION = ( ADDRESS_LIST = ( ADDRESS = ( PROTOCOL = TCP )( HOST = 192.168.X.XXX)( PORT = 1521 ) ) )( CONNECT_DATA = ( SERVER = DEDICATED )( SERVICE_NAME = XXXX ) ) ); User Id= xxxxxx; Password = xxxxxx;";
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
using (OracleConnection connection = new OracleConnection(GenerateConnectionString()))
{
connection.Open();
lblState.Text = connection.State.ToString();
OracleCommand oc = connection.CreateCommand();
oc.CommandText = "INSERT INTO TABLE (NO1, NO2, NO3, NO4, NO5, NO6, NO7, NO8, NO9, NO10, NO11, NO12, DATE) VALUES(1,2,3,1,1,1,'{txb_Textbox1.Text}',5,0.5,10,11,12,TO_DATE('09.07.2020 16:24:00', 'DD.MM.YYYY HH24:MI:SS'))";
oc.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show( "Exception: " + ex.Message );
lblState.Text = ex.Message;
}
}
I also installed all the necessary drivers for connecting to the oracle database and added the System.Data.OracleClient.dll as a reference to my c# project and added the "oraocci19.dll" and "oraocci19d.dll" file to the project file. I also added the oracle client to the system environment variables under PATH. Furthermore, I declared using System.Data.OracleClient;at the beginning of my overall code.
Please don't tell me that I do not use the latest Oracle Data Access Components (ODACs). I know that. We have a very old Oracle Database and I like the idea that I only need to install a few oracle dll's for it to work.
I just don't know what to do and spent the whole Friday and the whole weekend researching so that I could write to the Oracle database. I hope that someone experienced recognizes the problem directly and can help me.
Thank you very much in advance! :) Best regards
Edit1: Maybe I should try the other Oracle Data Access Components (ODACs) and their dlls. But normally my dll files should also work. A colleague of mine used my ODAC Installation and he said everything worked with it. But, he only had to read data from an Oracle table and not write in one.
Edit2: I got the problem! I was able to find the solution. Their was a mistake in my Oracle Prompt in the string. The C# code was correct. Here on stackoverflow I have of course reformulated and generalized the Oracle prompt string because it contains trusted data. The error was in the Oracle Command. This thread can be closed. Pete -S- got the right answer!
You could try this:
//Do the insert
oc.CommandText = "INSERT INTO TABLE (NO1, NO2, NO3, NO4, NO5, NO6, NO7, NO8, NO9, NO10, NO11, NO12, DATE) VALUES(1,2,3,1,1,1,'{txb_Textbox1}',5,0.5,10,11,12,TO_DATE('09.07.2020 16:24:00', 'DD.MM.YYYY HH24:MI:SS'))";
oc.ExecuteNonQuery;
//Retrieve in a separate action (you have to update your command to SELECT from INSERT)
oc.CommandText = "SELECT * FROM TABLE"; Statement
OracleDataReader reader = oc.ExecuteReader();
Another thing you can look at, is the CommandBuilder; but, it's the easy way out then a good solution. You can then specify the SELECT and the command builder will create the INSERT, UPDATE and DELETE commands.
Other thoughts
I don't think you can bind a data reader to a .DataSource. You can load a data table from a data reader, see this example.
Here is more information on DataAdapters and DataReaders
To UPDATE/INSERT: use .ExecuteNonQuery
To SELECT: there are different options, one is to build a DataTable via DataAdapaters and bind the data source using the data table.
You are doing it in the wrong order, you need to set the command text first and then execute the command (with ExecuteNonQuery() or ExecuteReader()):
OracleCommand oc = connection.CreateCommand();
oc.CommandText = "INSERT INTO TABLE (NO1, NO2, NO3, NO4, NO5, NO6, NO7, NO8, NO9, NO10, NO11, NO12, DATE) VALUES(1,2,3,1,1,1,'{txb_Textbox1}',5,0.5,10,11,12,TO_DATE('09.07.2020 16:24:00', 'DD.MM.YYYY HH24:MI:SS'))";
OracleDataReader reader = oc.ExecuteReader();
I'm trying to restore a database from a bak file. I found some code on how to do it grammatically but I'm not sure what I'm doing wrong. I'm getting an error:
Error:
Restore failed for Server 'www.freegamedata.com'.
I assume because i'm remotely connected? I'm not sure. The bak file is not on the server machine. I'm trying to build a desktop application that will install my database on the users server using my file. Here is my code:
private void Restore_Database()
{
try
{
Server server = new Server(Properties.Settings.Default.SQL_Server);
string filename = "Test.bak";
string filepath = System.IO.Directory.GetCurrentDirectory() + "\\file\\" + filename;
Restore res = new Restore();
res.Database = Properties.Settings.Default.SQL_Database;
res.Action = RestoreActionType.Database;
res.Devices.AddDevice(filepath, DeviceType.File);
res.PercentCompleteNotification = 10;
res.ReplaceDatabase = true;
res.PercentComplete += new PercentCompleteEventHandler(res_PercentComplete);
res.SqlRestore(server);
}
catch(Exception ex)
{
}
}
I'm not sure if I'm going about this the correct way. I'd like to add my database with my data to the users server as a base database. Am I doing something wrong? My connection string is good so I know its not a connection issue.
I have found a workaround for those whom do not have local access. This is a bit involved so I hope I explain this correctly and it makes sense.
Also note you will need to export your data to an excel spreadsheet before you do the steps listed below.
Exporting Data
Part 1:
Backup Your DATA!
This is a pretty simple process. Open SQL Management Studio and right click on your database. Choose export data and export it as an excel spreadsheet 2007. I'm not going to give detailed steps on this part because its pretty basic and you can google it. Sorry for the inconvenience.
Part 2:
Delete your database for testing purposes but make sure you have a working backup before you delete your database.
Importing Data
Part 1:
You need to create a script that will build your database for you automatically. You can do this by logging into SQL management Studio and right click on the database and choose:
Task -> Generate scripts
you should only need the default information. However, if your like me, I excluded the users in the list. This will generate a large SQL script.
Part 2:
Next you will want to store this file in your solution/project. Make sure you right click it and choose always copy or or copy if newer. I think that's the options. Basically it just copies your file when you debug or build it. This is critical because you will need to access this file to execute the script. Next you need to make a SQL function similar to mine to execute the script:
public bool SQLScript_ExecuteSQLScript(string ScriptLocation)
{
try
{
//5 min timeout
SqlConnection SQLConn = new SqlConnection(cn + "; Connection Timeout = 300;");
string script = File.ReadAllText(ScriptLocation);
Server server = new Server(new ServerConnection(SQLConn));
server.ConnectionContext.ExecuteNonQuery(script);
return true;
}
catch (Exception ex)
{
return false;
}
}
In my code sample please note I changed my timeout to 5 minutes. In the event you have a large script you may need to adjust the timeout to make sure your script fully executes.
Congrats you have rebuilt your database.
Part 3:
Load SQL Management Studio and make sure your database has been rebuilt successfully. You should see all your tables and Stored Procs but no data. If this is true, great you can continue. If not please go back and review your script. If you have SQL comments in your script, you may need to remove them. I had to in order for my script to execute without errors.
Part 4:
Now you need to import your data from your excel spreadsheet you created earlier. If your like me, you had multipal sheets. If you have multipal sheets then you will want to make a list to loop through each item in your list to import the sheets. If not then you can ignore my code on the list. I also put mine in a background worker but you don't need to depending on the size of your data. Also note I created a separate class containing my list but you dont have to do that if you don't want too. My sheet names are Table_1, Table_2 and Table_3 your will be differently most likely.
Sample Sheet List:
public List<string> GetTestTableList()
{
try
{
List<string> testlist = new List<string>();
testlist.Add("Table_1");
testlist.Add("Table_2");
testlist.Add("Table_3");
return testlist;
}
catch (Exception ex)
{
return null;
}
}
Part 5:
Next we will import the data from excel into SQL. This is a function I made but you can modify this to meet your needs.
Function:
private bool Import_Data_Into_SQL(string filepath, string SheetName, string Database, string Schema)
{
try
{
// sql table should match your sheet name in excel
string sqltable = SheetName;
// select all data from sheet by name
string exceldataquery = "select * from [" + SheetName + "$]";
//create our connection strings - Excel 2007 - This may differ based on Excel spreadsheet used
string excelconnectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" + filepath + " '; Extended Properties=Excel 8.0;";
string sqlconnectionstring = Properties.Settings.Default.SQL_Connection;
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(exceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(sqlconnectionstring);
bulkcopy.DestinationTableName = Database + "." + Schema +"." + sqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
I hope this helps. This was my workaround solution. Originally I wanted/tried to import my data using the .bak file but as pointed out above you can only do that if the sql server is local. So I hope this work around helps those who where faced with a similar issue as me. I'm not marking this as the answer because the above post answers the question but I'm posting this in case someone else needs this workaround. Thanks
Restore file must be on server. For installation use SQL script. This can be generated by SQL Server Management Studio (including data).
Right click on database. Choose "Tasks" - "Generate scripts". On second page of wizard choose "Advanced" and find "Types of data to script". Select "Schema and data" and save script to file.
Then use this code to run script on database
string scriptText = File.ReadAllText(scriptFile, Encoding.Default);
ExecuteBatch executeBatch = new ExecuteBatch();
StringCollection commandTexts = executeBatch.GetStatements(scriptText);
using (SqlConnection sqlConnection = new SqlConnection(conn))
{
sqlConnection.InfoMessage += SqlConnection_InfoMessage;
sqlConnection.Open();
for (int i = 0; i < commandTexts.Count; i++)
{
try
{
log.InfoFormat("Executing statement {0}", i + 1);
string commandText = commandTexts[i];
using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
log.Debug(commandText);
sqlCommand.CommandText = commandText;
sqlCommand.CommandTimeout = 300;
int r = sqlCommand.ExecuteNonQuery();
log.DebugFormat("{0} rows affected", r);
}
}
catch (Exception ex)
{
log.Warn("Executing command failed", ex);
try
{
sqlConnection.Open();
}
catch (Exception ex2)
{
log.Error("Cannot reopen connection", ex2);
}
}
}
sqlConnection.Close();
}
I want to insert values in "Navn" row and "Varenr" row in the DB table, when I'm clicking on a button. I have following code:
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"))
{
try
{
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
string col1 = textBox2.Text;
string col2 = textBox3.Text;
//generate sql statement
cm.CommandText = "INSERT INTO ProduktTable (Navn,Varenr) VALUES (#col1,#col2)";
//add some SqlParameters
SqlParameter sp_add_col1 = new SqlParameter();
sp_add_col1.ParameterName = "#col1";
//data type in sqlserver
sp_add_col1.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col1.Size = 20;
sp_add_col1.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col1);
//in your insert into statement, there are how many parameter, you must write the number of parameter
SqlParameter sp_add_col2 = new SqlParameter();
sp_add_col2.ParameterName = "#col2";
//data type in sqlserver
sp_add_col2.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col2.Size = 20;
sp_add_col2.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col2);
//open the DB to execute sql
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
But unfortunately, my data table is still empty:
I have set a breakpoint on the ExecuteNonQuery function, and it is triggered, when pressing on the button:
My table definition:
Your connection string is causing this:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"
|DataDirectory| Your database that is being updated in this method is in your App Data Directory while the one you are trying to retrieve data from is in your project folder...
|DataDirectory| is a substitution string that indicates the path to the database. DataDirectory also makes it easy to share a project and also to deploy an application. For my PC my App Data Directory is:
C:\Users\MyUserName\AppData\...
If you browse to this location and then go to following folders
...\Local\Apps\2.0\Data
You will be able to find your particular application directory probably stored with your assembly name, or some hash when you go there you will find it the database there is being updated just fine. This connection string is best for deployment.
You can also try this:
If you notice that Server Explorer is detecting all the databases on my PC and you can notice that there are couple of MINDMUSCLE.MDF files but all are at different paths, this is because there is one file in DEBUG directory, one in my PROJECT directory, one in my APP DATA directory. The ones starting with the numbers are stored in my APP DATA directories... If you select your respective database file and then run the SELECT query against it, you will get your data.
I made a tutorial some time ago. May be it will help you:
Check the value that ExecuteNonQuery is returning. It should return an int with the number of records affected by the SQL statement.
If it comes back with a value other than 0, then you know a record is being inserted somewhere. Before you close the connection, run a SQL query against the table to select all of the records and see if they come back through the code.
SELECT * FROM ProduktTable
If you get some records, then you may want to double check the database you're looking at through the IDE and the one your inserting records into through the code. It could be possible that you've got two different databases and you're querying one while inserting into another one.
Those are the steps that I would go through to help narrow down the issue and sounds like something I've probably done before. I hope it helps!
I've written the below function, which errors out correctly with non-int input and with int input returns that the audit was started properly. Unfortunately when I check the table I see that the data was never actually inserted.
Any suggestions for what I'm doing wrong?
public string SqlLocation = "Data Source="+ new FileInfo(Path.GetDirectoryName(Application.ExecutablePath) + "\\DRAssistant.sdf");
public string StartAudit(string sqlLocation, string dps)
{
int dpsInteger;
if (!int.TryParse(dps, out dpsInteger))
return "DPS is not a number!";
try
{
var myConnection = new SqlCeConnection(sqlLocation);
myConnection.Open();
var myCommand = myConnection.CreateCommand();
myCommand.CommandText = string.Format("SELECT dps FROM DispatchReviews
WHERE dps = {0}", dpsInteger);
SqlCeDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
{ return "DPS review has already started!"; }
myCommand.CommandText = "INSERT INTO DispatchReviews (dps, starttime,
reviewer) VALUES (#dps, #starttime, #reviewer)";
myCommand.Parameters.AddWithValue("#dps", dpsInteger);
myCommand.Parameters.AddWithValue("#starttime", DateTime.Now);
myCommand.Parameters.AddWithValue("#reviewer", Environment.UserName);
myCommand.Prepare();
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConnection.Close();
return "Dispatch Review Started!";
}
catch(Exception ex)
{ return "Unable to save DPS!" + ex.Message; }
}
Edit: Turns out this was just an idiot problem--which anybody looking at the SqlLocation could probably figure out--in that every time I built the application a new copy of the .sdf was copied into the application directory, overwriting the previous one. Also, the database I was checking for updates was not the one in the execution directory, but the one that was being copied into it, which is why it was always empty. I noticed this because when I tried to add the same DPS multiple times the first time I would get the DPS review started message, but subsequent attempts would give the error that it had previously been created.
Can you please show us your connection string??
Most likely, if you test this inside Visual Studio, the database file is being copied around (from your initial directory to the output directory where the app runs) and your INSERT will probably work just fine - but you're just looking at the wrong file when you check that fact.
For reasons beyond my control, I have to deal with a new Access MDB file that is downloaded, decrypted, and unzipped every month by an automated process I wrote. Despite the PGP encryption, the sender (an insurance company) refuses to send the MDB non-password-protected.
Unfortunately, immediately after the file is downloaded, it's processed, and is assumed to have no password, so these files aren't being processed due to an OleDbException showing that we have the wrong password. We know the password, and we know about the "with database password" option for connection strings:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
That only solves part of the problem, since another department needs to access the files later, and they don't know the password. So far, I've only been able to get it to work by holding Shift while I open the file, cancel at the password prompt, open the file again through an open Access process while holding Shift again and clicking "Open Exclusive", continuing to hold Shift while going through the password dialog, then unsetting the password through the security tools.
What I'd like to do is just programmatically unset the DB password on the MDB file as soon as it's downloaded, using C#. Is there a way to do that, or do I have to personally intervene every time we get a new file, completely defeating the purpose of automation?
The way to change the password programmatically is detailed here.
Essentially, one needs to do the following:
Open a connection to the database using ADO.NET
Execute an alter statement on the database setting it's password to NULL as so:
ALTER DATABASE PASSWORD [Your Password] NULL;
Dispose the connection
Sample code taken from the source:
Private Function CreateDBPassword(ByVal Password As String, _
ByVal Path As String) As Boolean
Dim objConn as ADODB.Connection
Dim strAlterPassword as String
On Error GoTo CreateDBPassword_Err
' Create the SQL string to initialize a database password.
strAlterPassword = "ALTER DATABASE PASSWORD [Your Password] NULL;"
' Open the unsecured database.
Set objConn = New ADODB.Connection
With objConn
.Mode = adModeShareExclusive
.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data " & _
"Source=[Your Path];"
' Execute the SQL statement to secure the database.
.Execute (strAlterPassword)
End With
' Clean up objects.
objConn.Close
Set objConn = Nothing
' Return true if successful.
CreateDBPassword = True
CreateDBPassword_Err:
Msgbox Err.Number & ":" & Err.Description
CreateDBPassword = False
End Function
In case anyone has to do something similar, here's what I wound up doing:
using System.Data;
using System.Data.OleDb;
namespace FTPAutomation.Utilities
{
public class AccessUtilities
{
public static void StripPasswordFromMDB(string currentPassword, string mdbFilePath)
{
var accessBuilder = new OleDbConnectionStringBuilder
{
Provider = "Microsoft.Jet.OLEDB.4.0",
DataSource = mdbFilePath
};
using (var conn = new OleDbConnection(accessBuilder.ConnectionString))
{
try
{
conn.Open();
return;
}
catch
{
// Do nothing, just let it fall through to try with password and exclusive open.
}
}
accessBuilder["Jet OLEDB:Database Password"] = currentPassword;
accessBuilder["Mode"] = "Share Exclusive";
using (var conn = new OleDbConnection(accessBuilder.ConnectionString))
{
if (ConnectionState.Open != conn.State)
{
conn.Open(); // If it fails here, likely due to an actual bad password.
}
using (
var oleDbCommand =
new OleDbCommand(string.Format("ALTER DATABASE PASSWORD NULL [{0}]", currentPassword), conn))
{
oleDbCommand.ExecuteNonQuery();
}
}
}
}
}