How to resolve : insert error column name or number of supplied values does not match table definition?
I have attempted to use the same data type used in the SQL database however when I run my program in visual studio C# I couldn't get the desired outcome I want
Try to specify the columns name you want to insert ("insert into yourTable (col1, col2) values (#para1, #para2);")
Also, I have never seem a paraneter being added like that. If the above doesn't work, try using Parameters.AddWithValue().
When dealing with connections, use:
using (var con = /*Connection declaration*/) {
con.Open();
// use connection here
}
This is important because, if you command fail, the connection will not be closed, meaning that soon, you server will be full of dead connections.
Related
I'm struggling to create a table using Npgsql.
using (NpgsqlCommand command = new NpgsqlCommand("CREATE TABLE #tableName(asdf TEXT)", con))
{
command.Parameters.Add(new NpgsqlParameter("#tableName", "test"));
command.ExecuteReader();
}
throws an exception:
Npgsql.PostgresException: '42601: syntax error at or near "$1"', which doesn't bring any clue to find out what is wrong.
How can I create a table using parameters? Is it actually possible?
Table names cannot be parameterized - you must integrate the name in your DDL string; parameterization is (among other things) about generating and reusing a single query plan regardless of the parameter's content, but that doesn't apply to CREATE TABLE statements.
If you need to create tables dynamically, you can use string interpolation, but be sure to escape properly to avoid SQL injection for user inputs.
I wanted to create a new database using the MySql.Data.MySqlClient with prepared statements. Unfortunately it shows me an error message "You have an error with your SQL syntax". Using "test" for the iv_name import value of the method.
When executing "CREATE DATABASE IF NOT EXISTS test;" directly in mysql server console, it works without any problems. When adding "'" to left and right of the #dbname a database will be created called #dbname in my mysql server.
public void CreateDatabase(string iv_name)
{
MySqlCommand lo_cmd = new MySqlCommand("CREATE DATABASE IF NOT EXISTS #dbname;", this._conn);
lo_cmd.Prepare();
lo_cmd.Parameters.AddWithValue("#dbname", iv_name);
lo_cmd.ExecuteNonQuery();
}
Here you can find a screen shot from the debuggin process
You cannot use parameters in data definition SQL statements like CREATE TABLE. Use string concatenation to create statements like that.
Be very careful with user-provided table names. Avoid punctuation and avoid reserved words like ‘select‘ and ‘table'. Your best bet is to reject any user input containing punctuation other than _, and to prefix user input with something like t_. So you reject table;droptable and turn mytable into t_mytable.
I'm trying to properly bind a Data Adapter to my SQL database to insert records submitted by a person in a c# program. I feel like I am 80% of the way, but now i've hit a hitch.
So as in the code below, I can create and bind a Data Table just fine. I've tested the delete functions and they work just fine. I am now attempting to have a 'save' button insert a new row to my database. The problem I have now is that a user is supposed to put in their 'notes' and then hit save. I auto populate the rest of the columns, but I do not know how to grab the notes that the user entered.
Here is my code so far:
string userVerify = User.CurrentUser.UserName.ToString();
int participantID = this.mParticipant.ParticipantID;
DateTime date = DateTime.Now;
string properRow = dtNotes[1, dtNotes.NewRowIndex - 1].Value.ToString();
sqlDataAdapter.InsertCommand = new SqlCommand("INSERT INTO xxMyDatabasexx (ParticipantID,Verifier,Notes,Date) VALUES (#participantID,#notes, #userVerify,#date);");
sqlDataAdapter.InsertCommand.Parameters.AddWithValue("#participantID", participantID);
sqlDataAdapter.InsertCommand.Parameters.AddWithValue("#userVerify", userVerify);
sqlDataAdapter.InsertCommand.Parameters.AddWithValue("#date", date);
sqlDataAdapter.InsertCommand.Parameters.AddWithValue("#notes", properRow);
sqlDataAdapter.Fill(dataTable);
sqlDataAdapter.Update(dataTable);
I am aware that the properRow variable's logic is wrong. Of course if there are no rows then the program will crash, but also if no new note has been entered it will just reproduce the last note entered which of course is wrong as well. When i look into my dataTable at the time of sqlDataAdapter.Fill, I can see the note in the correct column but I don't know how to simply save it.
Any help is appreciated. Thanks.
EDIT:
What I was unaware of is that the InsertCommand (naturally) also needs the ExecuteNonQuery command with it. I was under the assumption that since both Delete and Update did not, that Insert wouldn't either. This seemed to fix the issue. Thanks all for the help.
You can insert the record into SQL Database without need for DataAdapter just by using Command object as shown in the following code snippet (just pass your Insert SQL statement string):
void SqlExecuteCommand(string InsertSQL)
{
try
{
using (SqlConnection _connSqlCe = new SqlConnection("Conn String to SQL DB"))
{
_connSql.Open();
using (SqlCommand _commandSqlCe = new SqlCommand(CommandSQL, _connSql))
{
_commandSql.CommandType = CommandType.Text;
_commandSql.ExecuteNonQuery();
}
}
}
catch { throw; }
}
The general format of SQL INSERT query string is shown below:
INSERT INTO YourTable (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
You can further extend this solution by adding parameters to the SQL String/Command in order to protect against possibility of SQL injection (see the following example):
INSERT INTO YourTable (column1,column2,column3,...)
VALUES (#param1,#param2,#param3,...);
_commandSql.Parameters.Add("#param1","abc");
_commandSql.Parameters.Add("#param2","def");
_commandSql.Parameters.Add("#param3","ghijklm");
You can also use the alternative syntax for SQL Parameters, like for e.g.:
_commandSql.Parameters.Add("#param1", SqlDbType.NChar).Value = "abc";
_commandSql.Parameters.Add("#param2", SqlDbType.NChar).Value = "def";
_commandSql.Parameters.Add("#param3", SqlDbType.NVarChar).Value = "ghijklm";
Pertinent to your particular question, it should be like:
"INSERT INTO xxMyDatabasexx (ParticipantID, Verifier, Notes, [Date]) VALUES (#participantID, #userVerify, #notes, #dt)"
_commandSql.Parameters.Add("#ParticipantID",SqlDbType.NChar).Value= participantID;
_commandSql.Parameters.Add("#userVerify",SqlDbType.NChar).Value= userVerify ;
_commandSql.Parameters.Add("#notes",SqlDbType.NVChar).Value= properRow ;
_commandSql.Parameters.Add("#dt",SqlDbType.DateTime).Value= DateTime.Now;
Note: in case ParticipantID is the IDENTITY (i.e. Autonumber) Column, then do not include it in INSERT statement.
Hope this may help.
It seems to me that You are a bit lost. The way adapters are meant to work is
fill table from database via adapter (or take empty table)
bind table to GUI or manually transfer the information to GUI
change/add/delete data in table via binding or manually
update changes (inserts/updates/deletes) into database via adapter
The changes in table are automatically traced, so the adapter knows, what should be updated/inserted/deleted and use appropriate commands.
If You use adapter just as a holder for command You can ExecuteNonQuery with arbitrary parameters, You pass the whole concept and do not need adapter at all (see #AlexBells answer).
Apart from this, are You really going to write all that plumbing code by hand? Life is too short. If I were You, I would look for some ORM. You get simple CRUDs or concurrency checking with no effort.
The line cmd.ExecuteNonQuery();
cmd.CommandText
CREATE TRIGGER subscription_trig_0 ON subscription AFTER INSERT AS UPDATE user_data SET msg_count=msg_count+1 FROM user_data
JOIN INSERTED ON user_data.id = INSERTED.recipient;
The exception:
Incorrect syntax near the keyword 'TRIGGER'.
Then using VS 2010, connected to the very same file (a mdf file) I run the query above and I get a success message. WTF!
Options
The 1st line of the actual SQL sent is not CREATE TRIGGER
CommandType is wrong (eg it's trying to add EXEC or some "prepare" commands)
Use SQL profiler to see exactly what you're sending on to the DB engine (you actually have Express edition that is hosting the MDF)
Do you have CommandType set wrong?
I am not sure why this is failing but if I were you I would use SMO for ddl queries. In this case you need Trigger.Create Method.
It has been a while that i'm dealing with oracle and .net and they don't seem to be a perfect match together. That's this strange thing, i'm not finding any reason why it happens or how to fix it.
I do simple insert, update and delete and they are not working. It fails on the
cmd.ExecuteNonQuery();
Here's the piece of code:
sqlCommand = string.Format(#" INSERT INTO TABLE_1
(ID, NAME, DESCRIPTION)
VALUES ((SELECT MAX(ID)+1 FROM TABLE_1),'{0}','{1}')", name, description);
using (OracleConnection conn = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand(sqlCommand, conn);
cmd.CommandType = commandType;
try
{
conn.Open();
result = cmd.ExecuteNonQuery();
}
catch (Exception ex) { throw;}
finally
{
conn.Close();
}
a simple insert, right?! when i debug, i get the cmd.Text value (that would be the sqlCommand), and i do execute it in the oracle db, it goes just fine. As i go the point of executing it in .Net it gives up.
Is this a known situation? Is there any solution, any explanation for it?
Thnx in advance
This has nothing to do with your question but:
You should be using a sequence instead of selecting
(SELECT MAX(ID)+1 FROM TABLE_1) to genereate the id
I think you table is locked by someone. Or does the table have bitmap indexes? Bitmap indexes shouldn't be used in an environment where multiple user mutate data simultaneously because they lock a lot. Use BTree indexes in an oltp environment.
This has nothing to do with your question but:
When you work with Oracle you have to use parameterized queries instead of string.Format(..{}...). Parameterized queries are much faster because it means that Oracle doesn't have to parse every sql statement.
and do something like
create sequence table_1_seq
insert into table_1 (id, , ) values (table_1_seq.nextval, , ) to fill the id.
Instead of
(SELECT MAX(ID)+1 FROM TABLE_1)
because that doesn't work in a multi user environment.
Edit 1
You can run this select to find out if there are bitmap indexes present:
select index_name,table_name from all_indexes
where index_type = 'BITMAP';
Well, i think i just came out with a reasonable explanation:
the database should have been busy doing another update-delete or maybe insert operation, so you were waiting infinitely for it to do the update from the application.
i kind have your problem too. My question is:
How can we avoid this waits, or get a message "i'm bussy-try later" from the db, so that the users are aware of what happens?
Depending on how you're doing this; you can use:
catch (Exception ex)
{
System.Data.OracleClient.OracleException oEx = (System.Data.OracleClient.OracleException)ex.InnerException;
if (oEx.Message.IndexOf("ORA-0054") != 0)
{
.... do something here...
}
.. which will detect whether a lock has occurred. YMMV though as I've used this only on Oracle 9i.
I had the same problem. I didn't have a clue how to solve it. When I run program wihout sqldeveloper running it went just fine. My answer to this question: close any other programas that uses connection to oracle from your computer. It went just fine for me.
Insert:
insert into student values('rahul',474,'mca','phase2');
Delete:
delete from student where roll_no=472;
Update:
update student set address='phase7' where roll_no=474;
Commit any query used in Oracle client like Toad or SQL-Developer
parallely using oracle client(like Toad or sSQL-Developer) and .net is disallowed if you want to use both parallely then use commit in oracle client before using with .net.
Then try using it with .net - that will work.