When I update a field in my MySQL database, it always adds a whitespace to the value.
I tried to remove the whitespace with the trim-command and the replace-command. Neither of them worked. So I expect that it isn't a whitespace but some vague ASCII character. These are the commands I used:
this.foo = result.GetValue(0).ToString().Trim();
this.bar = result.GetValue(0).ToString().Replace(" ","");
The field it updates is a VARCHAR(xx). This is my MySQL update command:
MySqlCommand cmd = new MySqlCommand("UPDATE " + table + " SET " + new_field + " =' " + new_value+ "' WHERE " + field+ "= " + value + "",this.con);
this.con is my connection to the MySQL database.
FYI: I use .NET 3.5CF with a mysql.data.cf DLL in Visual Studio 2008.
Could someone help me out with this problem? It's driving me nuts.
Well yes, you've got a leading space in the SQL:
"UPDATE " + table + " SET " + new_field + " =' " + new_value+ "'
Note the bit straight after "=" - you've got a quote, then a space, then new_value.
However, you shouldn't be putting the values in the SQL directly in the first place - you should be using parameterized SQL statements... currently you've got a SQL injection attack waiting to happen, as well as potential problems for honest values with quotes in.
You should use parameterized SQL for both new_value and value here... I'm assuming that field and table come from more "trusted" sources?
This appears to have a space where the * is
" ='*" + new_value
Related
I'm trying to run this code from the ASP.Net code:
string strupdate = "Insert into registers(user, module, event_type)" +
"values (" +
"'" + user + "'," +
"'" + event + "'," +
"'" + source + "');";
/* connSQL it's the ODBC connection type: System.Data.Odbc.OdbcConnection */
connSQL.ExecuteNonQuery();
The query results into the following:
Insert into registers(user, module, event_type)values('user01','message','control');
Running this query from psql works perfectly fine, but running from the web returns the ODBC 07002 error with the following message: The # of binded parameters < the # of parameter markers
There is a typo in the "'" + event + "," + code, it should be "'" + event + "'," +.
i.e., ending single quote was missed in the second parameter value.
Note: Your code is possible for SQL Injection attack. Please convert the code with parameterised values.
When I insert in DB a string that contains special character as a "à" or a "é" from a FileInfo.GetFiles() item, I get issues and SQL save splitted special char. Non-special chars are OK.
For instance, "à" becomes "a`", and "é" becomes "e´". Did anyone get this kind of trouble?
Here is the code
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.GetFiles())
{
Logger.LogInfo("Info: " + fi.Name);
}
Basically, if string is "sàrl", log saved "Info: sa`rl"
When I breakpoint trough VS, I see the string with "à" but when I log it, char are splitted.
My SQL collation is Latin CI AS (SQL_Latin1_General_CP1_CI_AS) and DB already host string with special char without problem.
Thanks folks
EDIT
I have trouble when I insert the fi.Name into the final table too:
public bool InsertFile(string fileName, Societe company, string remark, PersonnelAM creator)
{
string commandText = (#"INSERT INTO [dbo].[TB_DOCSOCIETE_COM] " +
"([IdtSOC] " +
",[NomDOC] " +
",[RemDOC] " +
",[DateDOC] " +
",[IdtPER]) " +
"VALUES " +
"(#company" +
",#fileName" +
",#remark" +
",#date" +
",#creator) SELECT ##IDENTITY");
var identity = CreateCommand(commandText,
new SqlParameter("#fileName", DAOHelper.HandleNullValueAndMinDateTime<string>(fileName)),
new SqlParameter("#company", DAOHelper.HandleNullValueAndMinDateTime<int>(company.Id)),
new SqlParameter("#remark", DAOHelper.HandleNullValueAndMinDateTime<string>(remark)),
new SqlParameter("#date", DAOHelper.HandleNullValueAndMinDateTime<DateTime>(DateTime.Now)),
new SqlParameter("#creator", DAOHelper.HandleNullValueAndMinDateTime<int>(creator.id))
).ExecuteScalar();
return int.Parse(identity.ToString()) > 0;
}
I'm using NLog so data is varchar(8000) for message column and code that logs message is
public static bool LogInfo(Exception ex, string message = "")
{
try
{
GetLogger().Log(LogLevel.Info, ex, message);
}
#pragma warning disable 0168
catch (Exception exception)
#pragma warning restore 0168
{
return false;
}
return true;
}
EDIT 2 :
To be clear about DB, those 3 lines:
Logger.LogInfo("BL1 " + "sàrl is right saved");
Logger.LogInfo("BL2 " + fi.Name + " is not right saved");
Logger.LogInfo("BL3 " + "sàrl" + " - " + fi.Name + " is not right too!");
Gave me that result in DB:
BL1 sàrl is right saved
BL2 ENTERPRISE Sa`rl - file.pdf is not right saved
BL3 sàrl - ENTERPRISE Sa`rl - file.pdf is not right too!
So it doesn't come from DB, it is an issue about the string (encoding?)
varchar(8000)
Make the column NVARCHAR. This is not a collation issue. Collations determine the sort order and comparison rules, not the storage. Is true that for non-unicode columns (varchar) the collation is used as hint to determine the code page of the result. But code page will only get you so far, as obviously a 1 byte encoding code page cannot match the entire space of the file system naming, which is 2 bytes encoding Unicode based.
Use an Unicode column: NVARCHAR.
If you want to understand what are you experiencing, just run this:
declare #a nvarchar(4000) = NCHAR(0x00E0) + N'a' + NCHAR(0x0300)
select #a, cast(#a as varchar);
Unicode is full of wonderful surprises, like Combining characters. You can't distinguish them visually, but they sure show up when you look at the actual encoded bytes.
I am completely confused by SQLite right now.
I use the System.Data.SQLite Version for C#
I have two Tables:
Table 1:
In it I have created two columns (more but they are the important in this case and the statement is way to long to post it). The first one is called RecStat and the second one DOXinM.
Both are a Decimal and are created like this:
...
[RectStat] Decimal,
[DOXinM] Decimal,
...
The Create Table statement looks like this:
Create Table If Not Exists "Table1"
(..Columns..);
When I insert a value in this table the decimal works perfectly fine and when I read it out it works too on the xaml GUI.
After that I created a second Table which also has a Decimal Column.
I Created the table the same way (this is a short one, So i can give the whole statement)
Create Table If Not Exists "Table2" (
[ID] Integer Not Null Primary Key,
[Material] VarChar(10],
[Thickness] Decimal);
C# Code for the creation (Note that I work with a const string for all SQL Commands):
mySQLiteCommand.CommandText = #"" + DatabasePara.CREATE_SQL + " " + DatabasePara.TABLE_SQL + " " + DatabasePara.IF_SQL + " " + DatabasePara.NOT_SQL + " " + DatabasePara.EXISTS_SQL + " " + DBTableFilter.Filter + "
mySQLiteCommand.CommandText += #"([" + DBTableFilter.ID + "] " + DatabasePara.INTEGER_SQL + " " + DatabasePara.NOT_SQL + " " + DatabasePara.NULL_SQL + " " + DatabasePara.PRIMARYKEY_SQL + ", ";
mySQLiteCommand.CommandText += #"[" + DBTableFilter.Material + "] " + DatabasePara.VARCHAR_SQL + "(360), ";
mySQLiteCommand.CommandText += #"[" + DBTableFilter.Thickness + "] " + DatabasePara.DECIMAL_SQL + ");";
mySQLiteCommand.ExecuteNonQuery();
In both case I do the same insert for the Decimal Column:
Insert into Table1 ('RectStat') values ('10.5');
Insert into Table1 ('DOXinM') values ('1.3');
Insert into Table2 ('Thickness') values ('0.25');
For the Table2 Insert:
for (int FilterIndex = 0; FilterIndex < Database.FilterTable.FilterList.Count; FilterIndex++)
{
mySQLiteCommand.CommandText = #"" + DatabasePara.INSERTINTO_SQL + " " + DBTableFilter.Filter + "(" + DBTableFilter.Material + ", " + DBTableFilter.Thickness + ") ";
mySQLiteCommand.CommandText += #"" + DatabasePara.VALUES_SQL + " ('" + Database.FilterTable.GetFilterAt(FilterIndex).Material_Property + "', " + Database.FilterTable.GetFilterAt(FilterIndex).Thickness_Property + ");";
mySQLiteCommand.ExecuteNonQuery();
}
Now the Database inserts the first two Statements as 10.5/1.3 and the last one as 0,25
When I read out the value the first two works perfectly fine but the last one is shown without the numbers after the decimal "point".
So my question is.
Why does this happens?
(Btw I have more than 20 Decimals columns in my table and the "Thickness" is the only one with this problem)
I hope you can help me.
Thanks in Advance
Richard
What I have tried:
Tried different Values (Had the hope that it was because of the 0.25)
Tried it without the ''. But than the statement thought it had three values for two columns...
First of all, you should use parameterized queries. They will get rid of conversion problems and prevent sql injection. Most likely your issues are created by the fact, that your type of query creation calls decimal.ToString() implicitly. For certain locales, this replaces the . with a , which leads to a syntax error.
var query = "INSERT INTO yourtable COLUMNS(col1, col2, col3) VALUES(#p1, #p2, #p3)";
var cmd = new SQLiteCommand(query, connection);
cmd.Parameters.AddWithValue("#p1", 1);
cmd.Parameters.AddWithValue("#p2", 2.2);
cmd.Parameters.AddWithValue("#p3", "three");
cmd.ExecuteNonQuery();
This will, among other things, send the decimals to your server in a correct format, and also take care of possible ' quotes in your string literals and prevent sql injection, thus making your code more secure.
I have an odd issue that one would think is easy to solve. Basically I am creating a string like this:
string temp = "SET pagesize 50000;" + Environment.NewLine + "SET linesize 120;" + Environment.NewLine + sQuery.Text + Environment.NewLine + resultsQuery;
sQuery is an update statement and reslults query is showing a breakdown of the the results. Here is the results query. The update query is similarly formatted.
resultsQuery = "SELECT project_no, contact_date, SUM(CASE WHEN control_group = 'N' THEN 1 ELSE 0 END) \"CG = N\", SUM(CASE WHEN control_group = 'Y' THEN 1 ELSE 0 END) \"CG = Y\"" + "\r\n" +
"FROM OIC_TRACK_TEMP" + "\r\n" +
"WHERE job_no = " + tbJobNo.Text.Trim() + "\r\n" +
"AND cpm_customer_code = '" + lbClientID.Text.ToUpper() + "'" + "\r\n" +
"GROUP BY project_no, contact_date" + "\r\n" +
"ORDER BY contact_date, project_no;";
I then write the query to a command line:
updatessh.Write(temp);
The output in the command line looks like this:
SET pagesize 50000;
SET linesize 120;
UPDATE TABLE_NAME
SET PROJECT_NO = 'test'
.
.
How can I get rid of the double carriage returns in there? Oracle pukes when it sees them.
Thanks!
In my experience, SQL engines look at both \r and \n as newlines, so when including them with Environment.Newline, or in Windows, \r\n, you are getting both of those.
Try using \n instead of \r\n in your sql query.
You can replace doubled carriage returns with RegEx in final string, or just remove it before queries added. But if you always has them - just remove (dont add) + Environment
NewLine
I will be tested the application as windows application then it will be stored the datetime in MySQL data base.When I will be start this application using windows service it will be thrown this exception.
error [HY000][MySQL][ODBC 3.51 Driver] [MySqlid -6.0.11-alpha-community]incorrect datetime value " 5/6/2011 9:00:00 AM" for column column-name at row1
Windows application take the system format & my system format is yyyy-MM-dd hh:mm:ss
in windows service which format is used.
query18 += "select '" + obj8 + "' as DTvalue ,'" + date8 + "' as DTdatelogged1 ,'" + OpcGroup.QualityToString(e8.sts[counter8].Quality) + "' as DTquality ,'" + DateTime.FromFileTime(e8.sts[counter8].TimeStamp) + "' as DTtimestamp ,'" + e8.sts[counter8].HandleClient + "' as DTparamID Union " + Environment.NewLine;
UpdateQuery = Update parameter t Left join + Environment.NewLine;
UpdateQuery8 += ( + query18 + ) Temp on" + Environment.NewLine;
UpdateQuery8 += t.itemID=Temp.DTparamID+ Environment.NewLine;
UpdateQuery8 += set paramvalue=DTvalue, date_logged1=DTdatelogged1,Quality= DTquality,date_logged=DTtimestamp + Environment.NewLine;
UpdateQuery8 += where t.groupID=9 and t.itemID=Temp.DTparamID;
my query likethis timestamp value is 129500892576718750 it will be convert DateTime.FromFileTime() function converted value like '2011-05-17 12:30:57' in windows application it will be write into mysql database
but in windows service converted value like 2011/05/17 12:30:57 PM it will be not accepted by the MYSQL database same thing i will be used in the windows service
now
UpdateQuery8 = "Update parameter " + Environment.NewLine;
UpdateQuery8 += "set paramvalue=#paramvalue,date_logged1=#date_logged1,Quality=#Quality,date_logged=#date_logged" + Environment.NewLine;
UpdateQuery8 += "where groupID=9 and itemID=#itemID";
cmd8 = new OdbcCommand(UpdateQuery8, con136);
cmd8.Parameters.Add("#paramvalue", obj8.ToString());
cmd8.Parameters.Add("#date_logged1", date8);
cmd8.Parameters.Add("#Quality", OpcGroup.QualityToString(e8.sts[counter8].Quality));
cmd8.Parameters.Add("#date_logged", dt);
cmd8.Parameters.Add("#itemID",e8.sts[counter8].HandleClient);
cmd8.ExecuteNonQuery();
it will be execute but there no updation in database
Please help me in this regard.
Thanks in Advance.
Always use parametrized queries to pass data to the DB driver. Then it is up to the driver to format your dates correctly, and you avoid being susceptible to SQL-Injection attacks.
Create a datetime and format it the way YOU want. Not the system defaults, not the casual user defaults, the one you want.
DateTime dt = DateTime.Now;
String str = dt.ToString("yyyyMMdd");
This should lead to "20110517" if i'm not mistaking.
Bonus points are given if you use one of the better answers setting the code locale to the one used by the mysql server. But the one above should give you a way that works.