1

I'm trying to get file destination path using a text box and pass it into the database.(Developing in Visual Studio) When the query is running below error is displayed....

enter image description here

The method updateClark in the user class is shown below

public void updateClark(string _cid, string _path)
{
    SqlCommand cmd = new SqlCommand(@"UPDATE tbl_Path SET folder_path='" + _path + "' WHERE clark_id='" + _cid + "'", ConnectionDB.connection());
    cmd.ExecuteNonQuery();
}

What I missed in my code?

maccettura
  • 10,514
  • 3
  • 28
  • 35
E J Chathuranga
  • 927
  • 12
  • 27

5 Answers5

8

Now that you edited your question to include the actual relevant code, you should do something like this:

public void updateClark(string _cid, string _path)
{
    string command = "UPDATE tbl_Path SET folder_path=@folderPath WHERE clark_id=@clarkId";

    using (SqlCommand cmd = new SqlCommand(command, ConnectionDB.connection()))
    {
       cmd.Parameters.AddWithValue("folderPath", _path);
       cmd.Parameters.AddWithValue("clarkId", _cid);
       cmd.ExecuteNonQuery();
    }
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
3

If you use SQLParameters, the single quote will be handled correctly and you don't have to worry about SQL Injection (where someone can enter nested SQL commands in the textbox and they blindly get passed back to the server).

The code below assumes that the ConnectionDB.connection() method opens a new connection to the database. You should consider putting your disposable objects, like the connection and the command, in using blocks so that they are closed and disposed of automatically.

public static void updateClark(string cid, string path)
{
    var cmdStr = "UPDATE tbl_Path SET folder_path=@path WHERE clark_id=@cid";

    using (var con = ConnectionDB.connection())
    {
        con.Open();

        using (var cmd = new SqlCommand(cmdStr, con))
        {
            cmd.Parameters.AddWithValue(new SqlParameter("@path", path));
            cmd.Parameters.AddWithValue(new SqlParameter("@cid", cid));
            cmd.ExecuteNonQuery();
        }
    }
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • I'm wondering, from where did you gather that ConnectionDB.connection() has a ConnectionString field/property? – Camilo Terevinto Jun 20 '17 at 17:44
  • Because it's a [`SQLConnection`](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx) type (based on the signature of the method that it's being passed to) – Rufus L Jun 20 '17 at 17:45
  • In the OP's code, he doesn't need to open the Connection. What if ConnectionDB.connection() already creates a new SqlConnection and opens it? Why the need to create a new one when you have already opened one? (not that it's wrong, just wondering) – Camilo Terevinto Jun 20 '17 at 17:46
  • 1
    That's a good point, I'll update the sample since that's not really the issue at hand. Thanks! – Rufus L Jun 20 '17 at 17:49
1

This is how you should safely access DB without need to juggle your data.

private static void SqlCommandPrepareEx(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand(null, connection);

        // Create and prepare an SQL statement.
        command.CommandText =
            "INSERT INTO Region (RegionID, RegionDescription) " +
            "VALUES (@id, @desc)";
        SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int, 0);
        SqlParameter descParam = 
            new SqlParameter("@desc", SqlDbType.Text, 100);
        idParam.Value = 20;
        descParam.Value = "First Region";
        command.Parameters.Add(idParam);
        command.Parameters.Add(descParam);

        // Call Prepare after setting the Commandtext and Parameters.
        command.Prepare();
        command.ExecuteNonQuery();

        // Change parameter values and call ExecuteNonQuery.
        command.Parameters[0].Value = 21;
        command.Parameters[1].Value = "Second Region";
        command.ExecuteNonQuery();
    }
}

Code snippet stolen from MSDN

Marek Vitek
  • 1,573
  • 9
  • 20
  • 1
    You should also wrap the SqlCommand in a using block since it also (besides SqlConnection) implements IDisposable. Also passing null as the command text and then assigning it by hand is pretty weird (I do know that some MSDN examples are far from good) – Camilo Terevinto Jun 20 '17 at 17:30
  • 2
    I feel like some effort could be taken to make your code snippet more relevant to the OP, context is very helpful. – maccettura Jun 20 '17 at 17:41
  • 1
    There is a better answer that works with newly revealed code. I will leave this as it is. Maybe someone will find it useful. @Camilo - it was wrapped in using. But I am not C# programmer, it just hit me as the title screamed SQL injection to me. – Marek Vitek Jun 20 '17 at 17:59
0

There are many good answers above, just in case you look for an alternative.

public void updateClark(string _cid, string _path)
{
    string sql = String.Format("UPDATE tbl_Path SET folder_path={0} WHERE clark_id={1}",path,cId);
    SqlCommand cmd = new SqlCommand(sql, ConnectionDB.connection());
    cmd.ExecuteNonQuery();
}
Gokulan P H
  • 1,838
  • 1
  • 10
  • 13
-2

You need to replace a single quotation mark with two quotation marks. In your example above, it would seem to be the variable txtPath. The value "F:\Softwares\IDE's" would need to be passed in as "F:\Softwares\IDE''s" .

Good luck!

Eli
  • 2,538
  • 1
  • 25
  • 36
  • 5
    Nooooooooooo! He has written code that can be target of SQL injection. Either intentionally or unintentionally. He has to fix that code properly. This will not help as there are other characters that will break it. Proper solution is called **Prepared Statement** – Marek Vitek Jun 20 '17 at 17:23
  • Yeah sure. That is a smart answer. But I don't need to change it as `"F:\Softwares\IDE''s"` – E J Chathuranga Jun 20 '17 at 17:24
  • " are not valid in SQL. This answer is completely wrong. – Camilo Terevinto Jun 20 '17 at 17:28
  • 2
    E J Chathuranga it is your call what you will use, but be warned this approach has some undesirable consequences. When it is your school project, then I think it is fine. But I had to voice my concern as I have seen this approach a lot even on production systems. And that scares me. – Marek Vitek Jun 20 '17 at 17:37
  • When I posted my answer, the question had some different code - there was no indication of SQL Injection vulnerability. The code behind the updateClark method wasn't shown, hence the only issue at hand was the single-quote breaking the string in SQL. – Eli Jun 20 '17 at 17:38