I am writing a winforms program that gradually inserts into and reads from a MySQL database.
In PHPMyAdmin the fields I insert into are set to utf8_general_ci, and if I insert a row in the MyAdmin interface, it works perfectly. However, if I insert data on-the-fly using my program, certain special characters, like 'Ő' and 'Ű' are saved in the database as 'O' and 'U' respectively.
This is the code I am using:
MySqlConnection conn;
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = sql_string;
conn.Open();
MySqlCommand cmd = new MySqlCommand("", conn);
cmd.CommandText = "INSERT INTO projects (Projects_comment) VALUES (#Projects_comment)";
cmd.Parameters.AddWithValue("#Projects_comment", "ŐŰ");
cmd.ExecuteNonQuery();
conn.Close();
This however, appears as "OU" in the database. I believe the problem is with visual studio's coding. How can I change it, or how to resolve this problem?
Related
I'm working in Windows Forms and trying to use OLEDB to connect to an access .accdb file.
I can SELECT data without issue.
I can execute Insert and Create commands with no error.
But when I check the database afterward the data is not showing.
For example, when I create a new Table, the code will say the table was created and if I try to create the table again without closing the Windows Form it will throw an error saying the table already exists, but if I close and restart the program it will let me create the table once more.
Also, if I look into the Access file I wont see the table.
I've tried multiple tests both with Access open and closed. The Connection String is correct as I have made changes to tables in the Access file and they are reflected in the SELECT queries I've sent.
I suspect there must be a setting in Access I must enable for it to autocommit changes. But I haven't found it.
OleDbConnection conn = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =Database2.accdb");
string query = "INSERT INTO [TestTable] ([Test_Name], [Test_Number]) VALUES (?, ?)";
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("Test_Name", list_all_meters[0][0].Name);
cmd.Parameters.AddWithValue("Test_Number", list_all_meters[0][0].Value);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
Looks like the issue was I had set the Database "Copy to Output Directory" to Copy Always, which overwrote my changes every time I ran the program. Changing it to Copy if Newer fixed the issue.
I'm trying to open a connection to a DB and then insert a record into a table. At the moment it's just a simple localDB, I have looked at opening the connection with the sqlclient namespace methods.
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;
AttachDbFilename=C:\\FILE\\PATH\\EXAMPLE\\TechMVCDB.mdf;Integrated Security=True;
Connect Timeout=30");
I'm not certain that my connection string is even correct, I got it directly from the connection string box when you click on your database in the server explorer panel. I added a breakpoint in the code after the connection was opened and a select all statement was executed :
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\FILE\\PATH\\EXAMPLE\\TechMVCDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM Table ORDER BY Id";
SqlDataReader rdr = com.ExecuteReader();
I then get this error "System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.'" Table was just simply the name of the table was it also treating it as a keyword?
After this I changed the tablename to TechTester and ran it again, it ran with no errors and seemed to get the correct field amount of 4 id,sequence,direction,time it didn't seem to get the inserted test data.
I've also looked at using the Entity framework and implemented the very beginnings of it so I have my entity model class setup but nothing more. Is this the direction I should actually go with? How would I access the entity database?
My question is How do I best open a connection to a local db in asp.net-MVC using C#?
Table is one of the SQL Server reserved keywords.
I'm trying to insert data into a Microsoft Access Database.
I inserted data into the Access database, but the first and second time are the only times that show the data I inserted. When I rebuild my application, the data I inserted is gone. I don't know where they go and not show. I use C# with the .NET framework to develop. Here's the relevant part of the code:
OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString);
OleDbCommand com = new OleDbCommand();
com.Connection = con;
com.CommandText = "Insert into Language(English,Type,Thai) values(#eng,#type,#thai)";
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
con.Open();
com.ExecuteNonQuery();
I wrote that code, but I think it is strange. It doesn't show any errors or exceptions, but my data is not inserted correctly. Is this the correct way to insert data? If so, why it it not getting inserted?
When I rebuild my application, the data I inserted is gone
I suspect your database is being overwritten when the application is rebuilt.
This can happen, for example, if your application contains an MDB file that is copied to the output directory on build, and is used from the output directory.
I think Language should be a reserve word and you should wrap it in [] brackets.
Also consider wrapping the code in using blocks, like
using (OleDbConnection con = new OleDbConnection(...))
{
using (OleDbCommand com = new OleDbCommand(sqlString, con))
{
//code
}
}
Other than this [possible issue with table name and that you are not closing your connection], I don't see anything wrong with the code.
You define parameters for the query, but I don't see anywhere those parameters are bound to actual data...
Try some simple tests that replace the variables you're passing in as parameters with actual values, so you can isolate the problem:
In other words, replace this:
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
With something like this:
//I don't know the data types of your fields, so I'm guessing
com.Parameters.AddWithValue("#eng", "Test1");
com.Parameters.AddWithValue("#type", myEnum.Latin);
com.Parameters.AddWithValue("#thai", "Test1a");
If that works, then your problem probably lies with the english, type, and thai variables and you'll want to make sure they're getting the data you think they should be getting.
May be ur connection string not correct you can it by using .udl file
just follow the link
http://www.gotknowhow.com/articles/test-a-database-connection-string-using-notepad
You can also check the code shown below
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\ruby\\Desktop\\screenShots\\ruby.mdb;Persist Security Info=False");
con.Open();
OleDbCommand cmd = new OleDbCommand("insert into raj(Name,Roll) values('XYZ',12);",con);
cmd.ExecuteNonQuery();
when I run this sql:
insert into table1(ID,Name) values ('10','Saeed');
it seems that the record has been inserted, and if I read the table using (select * from table1) it shows me the inserted record, but after closing the program, it disappears.
it's the code:
string constr="Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|" +
"\\Database1.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('10','saeed');", con);
cmd.ExecuteNonQuery();
cmd.Close();
I inserted some records in it manually, and when I read the database, the manually inserted records exist.
It is not a transaction problem wont be solved with a transaction!
The issue sounds like you started a transaction and forgot to commit it. However, if you are using the exact code you posted this is not a transaction problem because you are not using one.
That makes me think there is something funky going on with your connection string.
For kicks and giggles trying changing your connection string to something like this
Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True;
Guess:
You are working with SQL Server Express and "Database1.mdf" within your project is configured (in properties window) for "Copy to Output Directory" value "Always"
Try to specify: "Initial Catalog=InstanceDB;" as well to make sure it does not create a new db name when you restart the application.
error in your code itself
its
con.Close();
not
cmd.Close();
there is no close method for SqlCommand
I agree with pascal. Sounds like the transaction isn't being committed.
(Edited to provide clearer code block from my Comment below)
con.Open();
trans = con.BeginTransaction();
SqlCommand cmd = new SqlCommand( "insert into st (ID,Name) values ('10','saeed');", con);
cmd.ExecuteNonQuery();
tran.Commit();
I have an MDB file I access using OleDB:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist Security Info=True");
And try to create a new row in a table Users:
connection.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO `users` (`name`, `password`) VALUES ('asd', 'asd')", connection);
cmd.ExecuteNonQuery();
connection.Close();
But nothing happens. I don't get an error message or exceptions, it runs without problems. But when I check the database after the program finished, the table still is empty.
(I already tried the same using DataSets and TableAdapters, but the same happened there: Inserting not committed to database)
That query does not look like an Access query. Have you tried:
"INSERT INTO [users] ([name], [password]) VALUES ('asd', 'asd')"
In Access, table and field names do not use a back-quote, however, reserved words must be enclosed in square brackets.