I create two table in my oracle (11g) database like this:
create table "test" ("id" int);
create table test ("id" int);
Then in my C# program there is a problem :
OracleConnection conn = new OracleConnection(-myConnectionString-);
conn.Open();
OracleCommand command = new OracleCommand("select * from test;", conn);
var v = command.ExecuteReader();
OracleCommand command = new OracleCommand("select * from \"test\";", conn);
var v = command.ExecuteReader();
for both command.ExecuteReader() I have an "ORA-00911: invalid character" error.
Remove ; (semi-colon) from the end of SQL string
In case other people wind up here looking for how to include multiple statements in a single command, you need to wrap your statements within begin and end. This will stop the invalid character errors due to the semi-colons. For example:
var command = new OracleCommand(#"
begin
select * from test;
select * from test2;
end;")
Why are you using semicolon in the query...It just be taken as invalid character.....
You have to remove the semicolon(;) from the query and do like this:
OracleConnection conn = new OracleConnection(-myConnectionString-);
conn.Open();
OracleCommand command = new OracleCommand("select * from test", conn);
var v = command.ExecuteReader();
OracleCommand command = new OracleCommand("select * from \"test\"", conn);
var v = command.ExecuteReader();
For more detail of this error, you can read here.
This isn't this guy's problem, but hopefully this will help someone out there:
I often have this problem with single quotes hidden inside inline comments, like so:
select foo
from bar
where
/* some helpful comment with a "can't" or somesuch */
baz='qux'
The unmatched single quote in the comment causes all kinds of drama, and oracle doesn't go out of its way to help you figure that out.
Replace the sqldatasource parameter ? with :Column_name in the delete, update and insert commands.
Related
So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.
I just want to know why we use "#" while inserting or updating or deleting data in sql table, as I used #name like below.
cmd.Parameters.Add(new SqlParameter("#fname", txtfname.Text));
See: SqlParameter.ParameterName Property - MSDN
The ParameterName is specified in the form #paramname. You must
set ParameterName before executing a SqlCommand that relies on
parameters.
# is used by the SqlCommand so that the value of the parameter can be differentiatd in the Command Text
SqlCommand cmd = new SqlCommand("Select * from yourTable where ID = #ID", conn);
^^^^^^^
//This identifies the parameter
If # is not provided with the parameter name then it is added. Look at the following source code, (taken from here)
internal string ParameterNameFixed {
get {
string parameterName = ParameterName;
if ((0 < parameterName.Length) && ('#' != parameterName[0])) {
parameterName = "#" + parameterName;
}
Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
return parameterName;
}
}
EDIT:
If you don't use # sign with the parameter then consider the following case.
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
cmd.CommandText = "SELECT * from yourTable WHERE ID = ID";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("ID", 1);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}
The above will fetch all the records, since this will translate into SELECT * from yourTable WHERE 1=1, If you use # above for the parameter ID, you will get only the records against ID =1
OK, no offense to the posters before me but I will try to explain it to you as simple as possible, so even a 7 year old understands it. :)
From my experience '#' in .SQL is used when you are "just not making it clear what exact data type or exact name will be used". "Later" you are pointing out what the exact value of '#' is.
Like, say, someone has developed some huge .SQL query which contains, say, the name of every person who has received it.
SELECT column_name,column_name FROM table_name WHERE column_name = #YOURNAME;
#YOURNAME = 'John Doe';
So, in this case, it's easier for everyone to just write their name at #YOURNAME and it will automatically convert the query to (upon launch):
SELECT column_name,column_name FROM table_name WHERE column_name = 'John Doe';
P.S: I am sorry for my syntax errors and incorrect terminology but I am sure you should have understood it by now. :)
Variables and parameters in SQL Server are preceded by the # character.
Example:
create procedure Something
#Id int,
#Name varchar(100)
as
...
When you create parameter objects in the C# code to communicate with the database, you also specify parameter names with the # character.
(There is an undocumented feature in the SqlParameter object, which adds the # to the parameter name if you don't specify it.)
Let's say that's my select query:
SELECT
CNDSC.NAME,
CNEA.ATRBT AS ATR,
ISNULL(CNEXTRA.CNVAL,'') AS CNVAL,
ISNULL(CNEXTRA.INRDR,'') AS INRDR
FROM
CNDSC
INNER JOIN CNEA
ON CNEA.ELEMS LIKE '%'+CAST(CNDSC.FNCELEM AS VARCHAR)+'%' AND
NOT CNEA.ELEMS LIKE '%1'+CAST(CNDSC.FNCELEM AS VARCHAR)+'%'
LEFT OUTER JOIN CNEXTRA
ON CNEXTRA.ATR LIKE CNEA.ATRBT AND
CNEXTRA.NAME LIKE #con
WHERE
CNDSC.NAME LIKE #con;
I am using C# to bind the result of that query on a datagrid. But when I try using the "auto-update" command of the SQLDataAdapter, I get an exception due to the use of more than one table in my select.
How would the UPDATE command look like, if I wanted to UPDATE the CNEXTRA.CNVAL table? And how could I ensure, if the CNVAL is empty that I will have to use the INSERT command?
Thank you for any help.
Depending on your version of SQL server you can use MERGE instead of UPDATE.
Something like:
DECLARE #CNVAL varchar(100) = 'test'
DECLARE #ATRBT varchar(100) = 'some attribute'
DECLARE #CON varchar(100) = 'the name'
MERGE into CNEXTRA as target
USING ( VALUES( #CON, #ATRBT, #CNVAL))
AS source([Name], ATRBT, CNVAL)
ON (target.ATRBT = source.ATRBT)
AND (target.[Name] = source.[Name])
WHEN MATCHED THEN
UPDATE SET
CNVAL = source.CNVAL
WHEN NOT MATCHED THEN
INSERT([Name], ATRBT, CNVAL)
VALUES(source.[Name], source.ATRBT, source.CNVAL)
;
A MERGE statement will perform an update if the record exists or an insert if it doesn't.
I haven't tested this code but something like this should work... (but you'll need to write your own insert, update and delete queries)
public static DataSet UpdateSqlRows(
string connectionString,
string selectQuery,
string insertQuery,
string updateQuery,
string deleteQuery,
DataSet dataSet)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand(selectQuery, connection);
connection.Open();
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
// Assign your own Insert/Update/Delete commands
adapter.InsertCommand = new SqlCommand( insertQuery );
adapter.UpdateCommand = new SqlCommand( updateQuery );
adapter.DeleteCommand = new SqlCommand( deleteQuery );
//Without the SqlCommandBuilder this line would fail
adapter.Update(dataSet);
return dataSet;
}
}
}
I'm trying to return the rowcount from a SQL Server table. Multiple sources on the 'net show the below as being a workable method, but it continues to return '0 rows'. When I use that query in management studio, it works fine and returns the rowcount correctly. I've tried it just with the simple table name as well as the fully qualified one that management studio tends to like.
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = sqlConnectionString;
cn.Open();
SqlCommand commandRowCount = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn);
countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count: " + countStart.ToString());
}
Any suggestions on what could be causing it?
Here's how I'd write it:
using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
cn.Open();
using (SqlCommand commandRowCount
= new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn))
{
commandRowCount.CommandType = CommandType.Text;
var countStart = (Int32)commandRowCount.ExecuteScalar();
Console.WriteLine("Starting row count: " + countStart.ToString());
}
}
Set your CommandType to Text
command.CommandType = CommandType.Text
More Details from Damien_The_Unbeliever comment, regarding whether or not .NET defaults SqlCommandTypes to type Text.
If you pull apart the getter for CommandType on SqlCommand, you'll find that there's weird special casing going on, whereby if the value is currently 0, it lies and says that it's Text/1 instead (similarly, from a component/design perspective, the default value is listed as 1). But the actual internal value is left as 0.
You can use this better query:
SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID)=N'YOUR_TABLE_NAME'
I am facing problem that. when I insert single quote in text field. on insertion it give exception of incorrect syntax near that particular field. why is it? does single quote has special meaning to sqlserver?
what if user what to enter word like don't , it's, or sometime by mistake enter single quote in start then it give exception. is there any sol to handle this? if single quote has issue with sqlserver.. then how to deal it?
use SqlParameter instead of string concatenation
This kind of expressions is worst thing you can do in your code, because at first you will have problem with data type convertion, and second the doors of Sql Injection is opem for hackers
string someQuery = "Select * from SomeTbl Where SomeTbl.SomeColumn = '" + tbSomeBox.Text+ "'" ;
Instead of that just use this
string someQuery = "Select * from SomeTbl Where SomeTbl.SomeColumn = #param";
SqlCommand someCommand = new SqlCommand(someQuery, conn);
someCommand.AddParams("#param",tbSomeBox.Text);
...
Hope this helps
SQL Server strings are enclosed (typically) in single quotes, so a single quote within a string will result in an error if you don't escape it prior to it being INSERTed.
Single quotes simply need to be doubled up, so the string Will''s World would result in Will's World making it's way into the data.
You will need to escape single quotes in SQL statements.
For example:
'don''t'
In SqlServer, if you want to insert string with quotes, use quotes twice before and after the string. For example you want to insert 'Hello', so insert it like '''Hello''' provided the field you want to insert in has string datatype like varchar etc.
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string")) {
con.Open();
SqlCommand cmd = new SqlCommand();
string expression = "(newsequentiali'd())";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name",
SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
}
}
}