update a column with / in mysql - c#

I am trying to update a column contains below value:
\\localhost\db\kkk\086018\ss\DocA\1_216925.jpg
with
\\localhost\db\kkk\086018\dd\DocA\1_216925.jpg
by using below C# code:
string str = "update my_document " +
"set path = replace (path,'" + fromFolder + "','" + toFolder + "')" +
"where doc_id in( select doc_id from patient_document where folder_id='" + id + "')";
str.Replace("\\", "\\\\");
Console.WriteLine(str);
using (MySqlConnection conn = new MySqlConnection(ECModel.Instance.ConnString))
{
using (MySqlCommand cmd = new MySqlCommand(str, conn))
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
what I observe that path submitting correctly to mysql but it wont reflect since between C# application and mysql, all the \\ convert to \ .
Would you mind advice me how to solve my issue?
I used # in front of my str also but that solution also didn't work.
** also I notice when I run my update statement with \\\\ it is working fine.

To try to keep this simple, I think the problem you're having is you effectively need both the "#" and the escape values. Try something like this. It worked for me. I made some assumptions on the data structures, and tested this on SQL Server, not MySQL, but I think the concept is sound and I reverted the code back to the MySQL client for you.
class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.updateTable("1", #"\\share\from\path", #"\\share\to\path");
Console.ReadLine();
}
private void updateTable(string id, string fromFolder, string toFolder)
{
string str = #"update my_document " +
"set path = replace (path,'" + fromFolder + "','" + toFolder + "')" +
"where doc_id in( select doc_id from patient_document where folder_id='" + id + "')";
str.Replace("\\", "\\\\");
Console.WriteLine(str);
using (MySqlConnection conn = new MySqlConnection(ECModel.Instance.ConnString))
{
using (MySqlCommand cmd = new MySqlCommand(str, conn))
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}

Related

ConnectionString Exception In Oracle database

I want to insert some data into an Oracle database through a C# application.
I keep getting an exception which looks like this : "The ConnectionString has not been properly initialized".
The code for inserting is bellow:
try
{
conn.openConnection();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn.Connection;
cmd.CommandType = CommandType.Text;
String sqlCommand = "INSERT INTO ComandaDVD (Id_Comanda,Id_Format,Data_Comanda,Id_TipPlata,Pret) VALUES (" +
"'" + txt_idComanda.Text + "', " +
"'" + txtFormat.Text + "', " +
"to_date('" + txtData.Text + "', 'DD-MM-YYYY'), " +
"'" + txtIdTipPlata.Text + "', " +
"'" + txtPret.Text + "')";
cmd.CommandText = sqlCommand;
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Comanda cu id_comanda[" + txt_idComanda.Text + "]a fost primita!");
}
else
{
MessageBox.Show("Eroare");
}
conn.closeConnection();
}
catch (Exception ex)
{
MessageBox.Show("Exceptie" + ex.Message);
}
}
I also made a personalized class to ease the connection handling:
class Conexiune_DB
{
private OracleConnection conn;
private static string CONNECTION_STRING = "Data Source=80.96.123.131/ora09;User Id=hr;Password=oracletest;";
public Conexiune_DB() { conn = new OracleConnection(CONNECTION_STRING); }
public void openConnection() { conn.Open(); }
public void closeConnection() { conn.Dispose(); }
public OracleConnection Connection
{
get { return conn; }
}
}
The exception appears to be because of 'conn.Open' in that class. Which is weird, because i made some insertions before, and i didn't have any problems.
Thanks in advance.
I'm quite sure this happens because you're opening your connection with conn.openConnection(); before you've even set a ConnectionString to it. So instead you should first set the ConnectionString to your conn before opening it. I'm not sure which connectionstring you'd like to use in this moment, but if it's the same, then just put conn.Conexiune_DB(); above conn.openConnection();

How do I insert a string with a back slash into a table using C#

I'm new to C#, am still teaching myself it and am coming from Visual FoxPro programming. The problem I have is I want to insert a value from a textbox in a form that only contains computer directories. In that field I select C:\ and when I run the code I get the error: Incorrect syntax near 'C:'.
The field name that contains the directory value is lblVault and is a label object.
The code I run looks like this:
using (SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\v11.0;" +
"AttachDbFilename=C:\\Development\\C-Sharp\\LockItUp\\Lockitup.mdf;Integrated Security=True"))
{
string stmt = "INSERT INTO Users(username,password,folderloc,fullname,email,cellphone) " +
"VALUES (" + #txtUsrName.Text + "," + #txtUserPassword.Text + "," + #lblVault.Text + "," +
#txtFullname.Text + "," + #txtEmail.Text + "," + #txtCellPhone.Text + ")";
using (SqlCommand cmd = new SqlCommand(stmt, connect))
{
try
{
connect.Open();
cmd.ExecuteNonQuery();
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
return;
}
}
}
Thanks for the help!
Easiest and safest way (google "SQL injection") is use parameters even with SQL queries. Not just it would take care of formatting strings for you, but also save you from simplest security problems.
using (SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\v11.0;" +
"AttachDbFilename=C:\\Development\\C-Sharp\\LockItUp\\Lockitup.mdf;Integrated Security=True"))
{
string stmt = "INSERT INTO Users(username,password,folderloc,fullname,email,cellphone) " +
"VALUES (#username,#password,#folderloc,#fullname,#email,#cellphone)";
using (SqlCommand cmd = new SqlCommand(stmt, connect))
{
cmd.Parameters.Add("#username",txtUsrName.Text);
cmd.Parameters.Add("#password", txtUserPassword.Text);
cmd.Parameters.Add("#folderloc",lblVault.Text);
cmd.Parameters.Add("#fullname", txtFullname.Text);
cmd.Parameters.Add("#email",txtEmail.Text)
cmd.Parameters.Add("#cellphone",txtCellPhone.Text);
try
{
connect.Open();
cmd.ExecuteNonQuery();
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
return;
}
}
}
Similar to how your connection string has extra slashes in it, you need extra slashes in your concatenated string to let C# understand the difference between a slash char, and a slash meant to escape into a different char. (For example \n means new line.)
#lblVault.Text.Replace(#"\", #"\\")
or
#lblVault.Text.Replace("\\", "\\\\")
The # symbol means don't allow any escaping. Slash means slash and only slash.

Problems in updating a SQL Server 2008 in C#. NET in runtime mode

I have faced a problem to update a row in SQL Serve 2008 via C#. NET application.
During runtime, the application tries to update the database but with no success. However, there is no exception, error, NOTHING. Checking the SQL Profile, the update command was sent, but not committed.
If I run the application debugging it step-by-step (via 'F11') the row is updated successfully (!?!?!?!?!)
I have copied the SQL update command and ran it on SQL Management Studio and also worked fine.
General Information:
- The only problem is in runtime mode.
- The user used is 'sa' with all granted permission
- I have ran the SAME METHODS for other tables (the only thing that changes is the table name) and it works fine.
The method responsible for it is:
public void Save(FormaResult obj)
{
try
{
bool insert = GetById(obj.SLABID) == null;
IList<string> colResult = GetColumns(TABLE);
List<string> colList = colResult.Where(TableColumns.Contains).ToList();
if (insert)
{
string col = string.Join(",", colList.Select(i => i).ToArray());
string colParam = string.Join(", ", colList.Select(i => "#" + i).ToArray());
QueryString = "INSERT INTO " + TABLE + " (" + col + ") VALUES(" + colParam + ");";
}
else
{
string colSet = string.Join(", ", colList.Select(i => i + " = #" + i).ToArray());
QueryString = "UPDATE " + TABLE + " SET " + colSet + " WHERE SLABID = #Id1;";
}
DbCommand = Conn.CreateCommand();
DbCommand.Connection = Conn;
DbCommand.CommandText = QueryString;
ListDbParameters = new List<DbParameter>
{
this.CriarParametro<DateTime>("GT_TIME", obj.GT_TIME),
this.CriarParametro<long?>("SLABID", obj.SLABID),
this.CriarParametro<short?>("STATUS", obj.STATUS)
};
if (!insert)
{
ListDbParameters.Add(this.CriarParametro<long>("Id1", obj.SLABID));
}
foreach (DbParameter param in ListDbParameters)
{
DbCommand.Parameters.Add(param);
}
Conn.Open();
DbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
TrkCGManagedModuleService.Logger.Error(ex.Message);
throw;
}
finally
{
Conn.Close();
}
}
I have also used this method:
public void OkEvt()
{
try
{
this.QueryString = "UPDATE " + TABLE + " SET STATUS = 1 " +
"FROM (SELECT TOP(1) * FROM " + TABLE + " WHERE STATUS=0 ORDER BY GT_TIME ASC) I " +
"WHERE " + TABLE + ".SLABID = I.SLABID AND " + TABLE + ".STATUS=0 AND " + TABLE + ".GT_TIME = I.GT_TIME;";
this.DbCommand = this.Conn.CreateCommand();
this.DbCommand.Connection = this.Conn;
this.DbCommand.CommandText = this.QueryString;
this.Conn.Open();
this.DbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
TrkCGManagedModuleService.Logger.Error(ex.Message);
throw;
}
finally
{
this.Conn.Close();
}
}
Both methods have the same aim, update the column 'STATUS' to '1'.
I would say the same thing as Soner Gonul about the SQL injection. I understand what your trying to do, but from my experience your leaving open a security door that is easily closed. Just requires a bit more time writing your CRUD statements for each table.
Here is a code sample that I use for my update queries you might find useful. If you are going to use this method, remember to create a user that has deny reader and deny writer. Then run a command to grant them execute permissions on all stored procedures.
this.o_ConnectionString is a private variable set inside my class constructor since i put my data layer in a separate project than my web applications.
public int UpdateThisTable(int TableUID, string SomeField)
{
string StoredProcedure = "usp_SomeStoredProcedure";
SqlConnection conn = new SqlConnection(enteryourconnectionstring);
SqlCommand cmd = new SqlCommand(StoredProcedure, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TableUID", TableUID);
cmd.Parameters.AddWithValue("#SomeField", SomeField);
conn.Open();
int rowsaffected = cmd.ExecuteNonQuery();
conn.Close();
return rowsaffected;
}

C# and MySQL - Incorrect Syntax?

Suppose I this method from my MySQLOperations class:
public bool checkIfRowExists(string tableName, string columnToLookIn, string dataToLookFor)
{
string myConnectionString = "Server = " + server + "; Database = " + dbName + "; UID = " + user + "; Password = " + password + ";";
int isExisting = 0;
using (MySqlConnection myConnection = new MySqlConnection(myConnectionString))
{
using (MySqlCommand myCommand = new MySqlCommand("SELECT EXISTS (SELECT 1 FROM #tablename WHERE #columnname = #data);", myConnection))
{
myCommand.Parameters.AddWithValue("#tablename", tableName);
myCommand.Parameters.AddWithValue("#columnname", columnToLookIn);
myCommand.Parameters.AddWithValue("#data", dataToLookFor);
try
{
myConnection.Open();
isExisting = (int)myCommand.ExecuteScalar();
myConnection.Close();
}
catch (Exception ex)
{
myConnection.Close();
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return (isExisting == 1);
}
}
}
And in another class, I created a MySQLOperations object.
I called on this method within an if statement: if(objSQLOperations.checkIfRowExists("tblInventory", "ItemID", txtItemID.Text)). Let us assume that txtItemID contains a valid 10-digit number. And that in my database, I have a table named tblInventory with a column ItemID.
My problem is that the statements within my catch block executes, saying there was an error with my SQL syntax. "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''tblInventory' WHERE 'ItemID' = '11111111111'' at line 1." is popped at a MessageBox when my txtItemID contains the text "1111111111".
I believe my SELECT EXISTS statement is correct.
No you can't use parameters for table or column names. You'll have to build up the SQL string dynamically by concatenation.
Like:
var sql = "SELECT EXISTS(SELECT 1 FROM " + tablename +
" WHERE " + columnNameToLookIn + " = #data);"
using (MySqlCommand myCommand = new MySqlCommand(sql, myConnection))
This of course opens you up to SQL injection if tableName and columnNameToLookIn can be user entered. However if the tableName and columnNameToLookIn are only set in code as it appears in your example then it is not a problem.
Related:
use a variable for table name in mysql sproc
Dynamic table names in stored procedure function

Getting "Invalid Operation. The Connection is closed" error while trying to update oracle from visual c# program

I've got a visual c# program running, but I'm getting a connection is closed error whenever I try to update. Here's what my code looks like:
private void Update()
{
try
{
String OneMachineScheduleOrder = "";
String series = "";
String oven = "";
String battery = "";
int x,y;
var sortedTextboxes = panel1.Controls
.OfType<TextBox>() // get all textboxes controls
.OrderBy(ctrl => ctrl.TabIndex); // order by TabIndex
foreach (TextBox txt in sortedTextboxes)
{
//Console.WriteLine(Convert.ToInt32(txt.TabIndex/2+1) + ": " + txt.Text);
OneMachineScheduleOrder = (txt.TabIndex / 2 + 1).ToString();
series = txt.Text.Substring(0, 1);
oven = txt.Text.Substring(1, 2);
battery = txt.Text.Substring(4).Trim();
if (Char.IsLetter(series[0]) && int.TryParse(oven, out y) && int.TryParse(battery, out x) && txt.Text[3].Equals('/'))
{
using (OracleConnection con = new OracleConnection(connectString))
{
OracleCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Oven_Master set SERIES = '" + series + "', OVEN = '" + oven + "', BATTERY = '" + battery + "' where ONE_MACHINE_SCHEDULE_ORDER = '" + OneMachineScheduleOrder + "'";
cmd.Connection = con;
cmd.ExecuteNonQuery();
Console.WriteLine(cmd.CommandText);
con.Close();
}
}
else { MessageBox.Show("Number: " + OneMachineScheduleOrder + " Is Invalid!"); }
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
Basically, I've got a bunch of textboxes on the form that are filled in in the format A01/01. I'm sorting the textboxes into a variable, and then for each textbox, I parse out the relevent data (OneMachineScheduleOrder, series, oven, and battery). If the data is in the right format, I use an oracleConnection with a connectionstring that is global (and I checked with the debugger that it has the correct value) to create an execute and OracleCommand. Otherwise, alert the user that the data is in the wrong format.
However, I'm getting an error that the connection is open. I tried putting a breakpoint on that line, and I'm getting that con = OracleConnection, so I can see that there is a connection. No idea where to go from here.
try calling connection.Open before executing your command
(yes, i know lol right)

Categories

Resources