I use
MySqlConnection con = new MySqlConnection("server=localhost;database=m1cleedb;uid=m1cleeuser;pwd=**;pooling=false");
MySqlCommand cmd = new MySqlCommand("insert into duyurular(adi, kim_icin, duyurulma_tarihi, detay) values(?p_1, ?p_2, ?p_3, ?p_4) ", con);
cmd.Parameters.AddWithValue("?p_1", duyuru_adi.Text);
cmd.Parameters.AddWithValue("?p_2", DropDownList3.SelectedItem.Text.ToString());
cmd.Parameters.AddWithValue("?p_3", duyuru_tarihi.Value.ToString());
cmd.Parameters.AddWithValue("?p_4", duyuru_editor.Value);
con.Open();
code block to insert a row inside my "duyurular" table.
I want to get turkish character support in this but whatever I tried, it didn't work.
I want to be able to put "ğ" char inside of ?p_1. but when I do this, it is inserted like "g".
Then, I decided to try it on my MySQL WorkBench side.
INSERT INTO `m1cleedb`.`duyurular`
(`adi`,
`kim_icin`,
`duyurulma_tarihi`,
`detay`,
`kategori`)
VALUES
('ğğ','ğğ','ğğ','şş','ğğ');
The result is frustrating.. It inserted the "ğ, ş" chars properly...
What could cause the difference between my asp.net insert command and my mysql workbench insert command? ://
I also did put some breakpoints and I saw that ?p_1 paramater's value really goes to "ğğ"..
Any help would be appreciated..
I believe you need to tell the connection what type of encoding you want to use.
MySqlConnection("server=localhost;database=m1cleedb;uid=m1cleeuser;pwd=**;pooling=false");
should be
MySqlConnection("server=localhost;database=m1cleedb;uid=m1cleeuser;pwd=**;pooling=false;CHARSET=utf8;");
C# Mysql UTF8 Encoding
Related
How to resolve : insert error column name or number of supplied values does not match table definition?
I have attempted to use the same data type used in the SQL database however when I run my program in visual studio C# I couldn't get the desired outcome I want
Try to specify the columns name you want to insert ("insert into yourTable (col1, col2) values (#para1, #para2);")
Also, I have never seem a paraneter being added like that. If the above doesn't work, try using Parameters.AddWithValue().
When dealing with connections, use:
using (var con = /*Connection declaration*/) {
con.Open();
// use connection here
}
This is important because, if you command fail, the connection will not be closed, meaning that soon, you server will be full of dead connections.
I am writing an application that must:
a.) Open an existing DBF file, then,
b.) Add a new empty record (row), then
c.) Add some data to one or more of the fields in the new record,
d.) Close the DBF file
I already have the code working to open and read the dbf file and display contents in a datagridview. That works perfectly. But I have searched for 3 days now, several hours a day, and cannot find anywhere any guidance or example on how to simply add a single blank record.
Note: the new record should simply be a new empty record, appended to the existing file (the file is automatically created by another application - so all the columns are established and do not need to be defined by my app)
Here is the code I am using to open and read the table, then count the rows.
OleDbConnection oConn = new OleDbConnection(
"Provider=VFPOLEDB.1;SourceType=DBF;Data Source=.\\;");
oConn.Open();
System.Data.OleDb.OleDbCommand oCmd = oConn.CreateCommand();
string dbname = "SELECT * FROM C:\\rmwin\\poslink.dbf";
oCmd.CommandText = dbname;
DataTable emp = new DataTable();
emp.Load(oCmd.ExecuteReader());
oConn.Close();
dg1.DataSource = emp;
int rowcount = emp.Rows.Count;
The data displays properly in dg1 (my datagridview control) So now what I want it to simply add a new record to POSLINK.DBF.
Any guidance will be greatly appreciated.
One sample showing SQL Update, but the principles are the same
To start, your OleDb connection source should point to the path where the data resides instead of just a relative path of .\ which might not always be a good choice. Then, all your queries for insert, update, delete are all operating from that folder so you don't have to be explicit of all paths. Just the table name.
OleDbConnection oConn = new OleDbConnection(
"Provider=VFPOLEDB.1;SourceType=DBF;Data Source=C:\\rmwin\\;");
Now, your command. To add, update and delete, you can do with relatively common sql statements. However, do not concatenate values you are trying to insert or update, that exposes you to SQL-Injection. Instead, the OleDb uses a "?" character as a place-holder for the parameter added to the command, and all "?" need parameters added in the same order.
So, to get a select, start as you have
System.Data.OleDb.OleDbCommand oCmd = oConn.CreateCommand();
oCmd.CommandText = "select * from PosLink";
for an insert, build the command out, identify all the fields you are trying to insert... obviously don't know the content of your table
oCmd.CommandText =
#"insert into PosLink
( TryColumn1,
TryColumn2,
TryColumn3 )
values
( ?,
?,
? ) ";
Now, add the parameters which come from wherever you have them from your screen/source
oCmd.Parameters.AddWithValue( "parmTryColumn1", yourCSharpClassOrPropertyStringField );
oCmd.Parameters.AddWithValue( "parmTryColumn2", DateTime.Now );
oCmd.Parameters.AddWithValue( "parmTryColumn3", 12345 );
Notice that the parameter naming I have prefixed with "parm" just for purposes to know its a parameter and not the actual column of the insert. They do have to be in the same order as the insert.
Then you can execute it... Since it is an INSERT, nothing is returned, so considered a non-query, but will return a count of how many records impacted... would expect 1 if all is ok, 0 or negative if a failure for anything else.
var recordCountInserted = oCmd.ExecuteNonQuery();
Hope this helps you get started and on your way.
As for doing an append blank, that would require a script. In VFP, you would do something like
use SomeTable
append blank
So, build a string for those commands (NOT ALL COMMANDS are supported within the VfpOleDb, but the most common you would expect data, date, string, common functions do work)
oCmd.CommandText =
#"execScript('use SomeTable
append blank
use' )";
oCmd.ExecuteNonQuery();
Yes, you can do VFP code like this, but not everything is allowed
Many other links from my history posting for VFP, OleDb, parameterized queries, etc. There are also other strong VFP developers in this community too.
I am working on a C# windows form which is connected to MySQL and updates strings within the form. I have everything working properly except for a small issue.
Say you want to update the "notes" field to read "The dog's bone", that apostrophe is causing the SQL query to end and cause an error. How can I get around this please?
UPDATE `database`
SET `notes` = 'The dog's bone'
WHERE `Pet` = 'Dog';
Thanks!
You can escape ' character in MySQL with doubling it like ''.
Other than that, if you use parameterized queries, you will not need this at all. Just pass your The dog's bone string directly to your parameterized query and you will be fine.
Also I strongly suspect you try to use UPDATE instead of SELECT statement. In MySQL, SELECT syntax doesn't have any SET part.
And using a reserved keyword as a column name is a bad idea. As a best practice, change your database column name to non-reserved word.
using(var con = new MySqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"UPDATE `database` SET notes = #notes
WHERE Pet = #pet";
cmd.Parameters.AddWithValue("#notes", "The dog's bone");
cmd.Parameters.AddWithValue("#pet", "Dog");
con.Open();
cmd.ExecuteNonQuery();
}
I used AddWithValue method as an example in my code since I didn't know your column types but you don't use it. This method may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.
Escape it with another single quote ':
SELECT `database`
SET `notes` = 'The dog''s bone'
WHERE `Pet` = 'Dog';
I have an insert statement that takes the raw text from text area and stores it. We only allow editing the same value and not display them.
During the insert the newline along with slash [abc\\ndef] is removed for some reason by SQL Server. So what is the C# solution to this?
Insert Statement
INSERT INTO Comments (Comment) VALUES (#clientValue)
where comment is the column name and #clientValue contains the string abc\\ndef when viewed in the Visual Studio debugger
Demonstration
SELECT 'abc\
def' AS ColumnResult;
C# Command Snippet
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Comments(Comment) VALUES (#clientValue)"
cmd.Connection = conn;
SqlParameter param = new SqlParameter();
param.ParameterName = "#clientValue";
param.Value = txtComment.Text;
cmd.Parameters.Add(param);
conn.open();
execute the statement here
running above statement the \ and \n newline from the textarea are getting removed. How do I avoid this?
What is the column type for the storage column? If it is varchar or text then change it to nvarchar/ntext.
If any of that doesn’t work you can simply replace /n with something like or use html but it would require that you update the string before storing it in database and before adding it back to textarea. This is far from ideal solution but it would work.
Please help me to store apostrophe. I m creating a website (C#, .net, SQL Server) and want to have a message box for the users but the problem is that when I inserts any message such as John's it shows an error near ''s'.
Please tell me how could I store apostrophe in database
I used nvarchar, varchar and everything but failed to store apostrophe containing messages.
A general solution is to write message with double apostrophe but this is not a solution for a website
You are open for SQL-Injection. Don't concatenate strings to build your query. Instead use SQL-Parameters. That also makes your code more readable and prevents errors like yours.
Here's an example:
int amt;
using (var con = new SqlConnection(ConnectionString)) {
var sql = "INSERT INTO dbo.Message(UserID, Message) VALUES(#UserID, #Message);";
using (var cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("#UserID", userID); // passed as argument
cmd.Parameters.AddWithValue("#Message", txtMessage.Text); // f.e. "John's"
con.Open();
int inserted = cmd.ExecuteNonQuery();
}
}
The same works also with other sql like UPDATE commands.
The problem is that you need to escape Apostrophe by another Apostrophe.
For example have a look at:http://sqlfiddle.com/#!3/d2f75/1
CREATE TABLE tblTEst( col1 NVARCHAR(50))
INSERT INTO tblTest
(Col1)
SELECT 'John''s'
The best solution is to use a prepared statement (or whatever the equivalent in C# is) where your SQL only contains placeholders and you pass the actual values through a different method.
In a character literal, the single quote ' can be used by simply doubling it:
insert into foo (bar)
values
('John''s');
use CHAR(39)between john & s like this: 'john'+CHAR(39)+'s'