I have a SQL query:
String S = Editor1.Content.ToString();
Response.Write(S);
string sql = "insert into testcase.ishan(nmae,orders) VALUES ('9',#S)";
OdbcCommand cmd = new OdbcCommand(sql, myConn);
cmd.Parameters.AddWithValue("#S", S);
cmd.ExecuteNonQuery();
Error: Column 'orders' cannot be null at System.Data.Odbc.OdbcConnection.HandleError
From the manual:
When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder. For example:
SELECT * FROM Customers WHERE CustomerID = ?
The order in which OdbcParameter objects are added to the OdbcParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
Use this:
string sql = "insert into testcase.ishan(nmae,orders) VALUES ('9', ?)";
OdbcCommand cmd = new OdbcCommand(sql, myConn);
cmd.Parameters.AddWithValue("you_can_write_anything_here_its_ignored_anyway", S);
cmd.ExecuteNonQuery();
it will be helpful to you
cmd.Parameters.Add("#S", OdbcType.Char, S);
Related
I am inserting a record in DB, I am using inline query, I have to get the generated ID, this is how I am doing this
var query = "INSERT INTO [Users] ([Username],[Password]) VALUES(#username,#pwd) SELECT #ID = SCOPE_IDENTITY()";
OleDbParameter[] queryparam = new OleDbParameter[3];
queryparam[0] = new OleDbParameter("#username", OleDbType.VarChar);
queryparam[0].Value = "username";
queryparam[1] = new OleDbParameter("#pwd", OleDbType.VarChar);
queryparam[1].Value = "123456";
queryparam[2] = new OleDbParameter("#ID", OleDbType.Integer);
queryparam[2].Direction = ParameterDirection.Output;
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = DBConnectionHelper.getConnection();
myCommand.CommandText = query;
myCommand.Parameters.AddRange(queryparam);
adapter.InsertCommand = myCommand;
myCommand.ExecuteNonQuery();
I am getting error:
Must declare the scalar variable "#ID".
Must declare the scalar variable "#username".
I also tried using (int)myCommand.ExecuteScalar() but no luck.
How can I get generated ID in this case?
From OleDbCommand.Parameters:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text1. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
So, for your code your query should be:
INSERT INTO [Users] ([Username],[Password]) VALUES(?,?) SELECT ? = SCOPE_IDENTITY()
1Which is the default, so is what your code is using.
From what I can make out of your question, you have declared a variable called query and written your query inside it. Also, your parameter declaration seems to be correct.
Now the problem might be in this line :
myCommand.CommandText = _query;
The variable is query and here you are using _query. So that is probably why the parameters are not added for that particular query and hence the error. It should be like this :
myCommand.CommandText = query;
Hope this clears.
Instead of Select Use Set #Id=Scope_Identity()
I need to bind parameters on ODBC query from C#. This is the sample code, but VS tells me that there's one parameter missing.
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM user WHERE id = #id";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
What is the syntax for binding values on ODBC?
Odbc cannot use named parameters. This means that the command string uses placeholders for every parameter and this placeholder is a single question mark, not the parameter name.
OdbcCommand.Parameters
Then you need to add the parameters in the collection in the same order in which they appear in the command string
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE id = ?";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
You have also another problem, the USER word is a reserved keyword per MS Access Database and if you want to use that as field name or table name then it is required to enclose every reference with square brackets. I strongly suggest, if it is possible, to change that table name because you will be hit by this problem very often.
use "?" in place of # if you are using ODBC.
Try to do as follows:
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM user WHERE id = ?";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
To use ODBC parameterized LIKE carry out as follows, i.e. you do not use the typical single quotes or even put the % in the CommandText (Furthermore I think perhaps the %? has a special meaning for Oracle? :
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE name LIKE ?";
cmd.Parameters.AddWithValue("#fieldName", OdbcType.NVarChar).Value = "%" + nameFilter + "%";
I iterate over an external source and get a list of strings. I then insert them into the DB using:
SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();
Where commandString is an insert into command. i.e.
insert into MyTable values (1, "Frog")
Sometimes the string contains ' or " or \ and the insert fails.
Is there an elegant way to solve this (i.e. #"" or similar)?
Parameters.
insert into MyTable values (#id, #name)
And
int id = 1;
string name = "Fred";
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("name", name);
command.ExecuteNonQuery();
Now name can have any number of quotes and it'll work fine. More importantly it is now safe from sql injection.
Tools like "dapper" (freely available on NuGet) make this easier:
int id = 1;
string name = "Fred";
connection.Execute("insert into MyTable values (#id, #name)",
new { id, name });
You should look into using parameterized queries. This will allow you insert the data no matter the content and also help you avoid possible future SQL injection.
http://csharp-station.com/Tutorial/AdoDotNet/Lesson06
http://www.c-sharpcorner.com/uploadfile/puranindia/parameterized-query-and-sql-injection-attacks/
i want to insert to a sql table a string that might contain ' character.
what is my best way to do so ?
should i insert a \ before the ' ?
here's my command in a c# code:
SqlCommand myCommand = new SqlCommand(
String.Format(
"insert into ACTIVE.dbo.Workspaces_WsToRefile values({0},'{1}',getdate())",
folderId,
NewWorkspaceName),
myConnection);
where NewWorkspaceName might contain ' character, so the insert will cause an exception at the moment.
thanks in advanced, hadas.
You should be using SqlParameter. http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx
string query = "insert into ACTIVE.dbo.Workspaces_WsToRefile values(#folderID, #newWorkSpace, #createDate)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#folderID", folderId);
param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(param);
.....
}
You have only one option, forget everything else. Use Parametrized queries like this
SqlCommand myCommand = new SqlCommand("insert into ACTIVE.dbo.Workspaces_WsToRefile" +
" values(#id, #space, getDate()", myConnection);
myCommand.Parameters.AddWithValue("#id", folderId);
myCommand.Parameters.AddWithValue("#space", NewWorkspaceName);
myCommand.ExecuteNonQuery();
folderID and NewWorkspaceName, are passed to the Sql Engine inside parameters.
This will take care of special characters like quotes.
But you gain another benefit using parametrized queries. You avoid Sql Injection Attacks
NewWorkspaceName= NewWorkspaceName.Replace("\'","\'\'");
'' is a ' in sql
You can try this:
string stringToDatabase=Server.HtmlEncode("կҤїАͻBsdҤїА");
This saves 'stringToDatabase' in your database
. Then while retreiving
string OriginalText=Server.HtmlDecode(stringFromDatabase);
I have a sql select statement in my VS2005 C# server-side coding for a web application and I am meeting some errors.
Below is a screenshot of the controls in the webpage:
Data Source SqlDataSource1 : Query:SELECT [Name] FROM [Users].
Dropdownlist UserNameList : Lists all userName retrieved from SqlDataSource1.
Checkboxes AdminCb and UserCb : Automatically checks if the userType of the userName is as.
Button loadUser : Gets the user type and checks the check boxes accordingly.
Below is my code for my loadUser button
SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
if(sql== "Administrator"){
AdminCb.Checked=true;
}
if(sql== "User"){
UserCb.Checked=true;
}
Currently I am stuck with the error (Wong is the 2nd word of the user's name):
Questions:
1) How can change my Sql query so that it can take in more than 1word?
2) And will I be able to check boxes once I am able to run my sql query?
Thank You.
You must have to use Parameter and call the ExecuteScalar() method instead of ExecuteNonQuery().
string sql = "SELECT [User Type] FROM [Users] where [Name]=#Name";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name",SqlDbType.VarChar,50).Value=UserNameList.Text;
conn.Open();
Object result=cmd.ExecuteScalar();
conn.Close();
if(result!=null)
{
string usertype=result.ToString();
if(usertype=="Administrator")
{}
else
{}
}
In case, if result returned from the database contains more then one rows then use ExecuteReader() method.
string sql = "SELECT [User Type] FROM [Users] where [Name] like #Name";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name",SqlDbType.VarChar,50).Value="%" + UserNameList.Text + "%";
conn.Open();
SqlDataReader result=cmd.ExecuteReader();
while(result.Read())
{
///
}
result.Close();
conn.Close();
Since you are concatenating the SQL string, if the input itself has a single quote in it, it thinks this is the end of the input, and the continuing input is SQL statements, which is why you may be getting that error.
Switch to using a parameter, or make sure any single quotes are escaped as a pair of single quotes, like:
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text.Replace("'", "''"));
Since the error is indicating there is something wrong with the Name, I would take a closer look at this line:
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text);
If you are using string.Format, you might as well use it
string sql = string.Format("SELECT [User Type] FROM [USERS] where Name like {0}", UserNameList.Text);