I am trying to insert a integer into a database in C# using the code below, but everytime I run the compiler informs me that my integer is not a valid column "Invalid Column Name UserID"
Does anyone have any insight on this? Thanks.
Console.WriteLine("Please enter a new User Id");
string line = Console.ReadLine();
int UserID;
if (int.TryParse(line, out UserID))
{
Console.WriteLine(UserID);
Console.ReadLine();
}
//Prepare the command string
string insertString = #"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES (UserID,'Ted','Turner')";
First things first, I would get into the habit of using parameterised queries, if you are not planning to use stored procedures. In your example, I would:
using (var command = new SqlCommand("INSERT INTO tb_User(ID, f_Name, l_Name) VALUES (#id, #forename, #surname)", conn))
{
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("forename", forename);
command.Parameters.AddWithValue("surname", surname);
command.ExecuteNonQuery();
}
Where id, forename, surname are the appropriate variables. Notice I am also using using blocks, this ensures that my objects are cleaned up after it has completed.
it is because the 'UserID' within your insertString : ..."VALUES (UserID"... is invalid.
you need to pass a value for the UserID such as: ..."VALUES ('myUserIDGoesHere'"...
Your string is not dynamically reading the variables. Use something like this:
string insertString =
string.Format(#"INSERT INTO
tb_User(ID,f_Name, l_Name) VALUES
({0},'{1}','{2}')", UserId, "Ted",
"Turner");
There are better ways depending on what kind of data access you're using, but this is just to make the point of how to correct the string.
The problem is the first argument in VALUES - it simply isn't defined. If this is meant to be the value the user has entered, then you need to add a parameter to the command and use that parameter in the SQL; for example:
cmd.Parameters.AddWithValue("#id", UserID);
An then use
VALUES(#id, ...
in the TSQL.
Also, generally you might want to have the system generate the unique id. A the simplest level this could have an IDENTITY defined (an automatic sequence).
Use a parameterized query:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var insertCommand = new SqlCommand(
#"INSERT INTO tb_User (ID, f_Name, l_Name)
VALUES (#ID, 'Ted', 'Turner')", connection))
{
insertCommand.Parameters.AddWithValue("#ID", userID);
insertCommand.ExecuteNonQuery();
}
}
To answer your question regardless of your approach, try:
string insertString = #"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES ("
+ UserID + ",'Ted','Turner')";
Related
I Have a website which creates new order and saves shopping bag items into database.
The thing is that insert into,select,update,delete sentences are working in all my tables except one, i think i wrote the sentence perfectly but its still throw excption that says something wrong with the sentence.
string OrderSql = string.Format(#"
INSERT INTO Order ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend])
VALUES ({0},{1},{2},{3},'{4}')",
UserId, DateTime.Now, Price, 1, Address);
at first i thought the problem may be found at the db so i copied my db into new once still doesnt working
i would send the relationship between tables but i need 10 rep..
It looks like you have two issues. Firstly as #juergen points out in the comments order is a reserved word so you'll need to enclose it in square brackets. Secondly, you don't have the date enclosed in quotes. So your code should read:
string OrderSql = string.Format(#"INSERT INTO [Order] ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend])
VALUES ({0},'{1}',{2},{3},'{4}')", UserId, DateTime.Now, Price, 1, Address);
Note the square brackets around Order and the single quotes around {1}.
However, you are open to SQL Injection attacks using that code so I would strongly suggest you read up on using parameterized queries. #DJ KRAZE has added a link in the comments to this question which should point you in the right direction.
you can also create a method call it and do something like this.
This would require that you create a stored procedure with the #Parameters shown in this example ** if this is Access then petelids Answer will be a great starting point if this is SQL Server then what I have posted would work for you
private void InsertMyData(string UserId, DateTime DayMonthYear, double Price, string Address)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO [Order] ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend])
VALUES (#UserId, #DayMonthYear, #Price, 1, #Address)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#UserId", UserId);
cmd.Parameters.AddWithValue("#DayMonthYear", DayMonthYear);
cmd.Parameters.AddWithValue("#PriceToPay", Price);
cmd.Parameters.AddWithValue("#StatusID", 1);
cmd.Parameters.AddWithValue("#AdressToSend", Adress);
connection.Open();
cmd.ExecuteNonQuery();
}
}
I'm trying to create a registration page using C# on Visual Basic 2012. When I debug I get 0 errors, but when I try to register an account I get the following error.
"Incorrect syntax near ')'"
If I try to create an account with an existing username it says that username already exist. So I'm able to connect to the SQL server, but I'm not sure where I went wrong.
This registration page should create accounts in my DB DNMembership> Table> Accounts
Here is my code I'm working with.
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString);
con.Open();
string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#AccountName", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Passphrase", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#Country", DropDownListCountry.SelectedItem.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch(Exception er)
{
Response.Write("<b>Something Really Bad Happened... Please Try Again.< /br></b>");
Response.Write(er.Message);
}
What did I do wrong?
Looks like you forget to add VALUES part in your INSERT command.
VALUES
Introduces the list or lists of data values to be inserted. There must
be one data value for each column in column_list, if specified, or in
the table. The value list must be enclosed in parentheses.
Change your sql query like;
string insCmd = #"Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES(#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)";
And use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString))
{
using(SqlCommand insertUser = new...)
{
//Your code..
}
}
You haven't specified any parameters in your SQL, or a VALUES section - you're saying "I want to insert into these fields..." but not what you want to insert. It should be something like:
string insCmd =
"Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) "
+ "Values (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country");
You need to change the SQL statement:
string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) VALUES (#AccountName,#Passphrase,#EmailAddress,#FullName,#Country)";
You are missing part of Insert statement
INSERT INTO table (col1, col2) VALUES (#col1, #col2)
Or if you want to insert all values into columns in order they are in table
INSERT INTO table VALUES (#col1, #col2)
There is several alternatives for INSERT command in SQL Server.
Specify COLUMNS and after that specify VALUES
SQL Syntax - INSERT INTO TABLE(AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES ('AccountName', 'Passphrase', 'EmailAddress', 'FullName', 'Country')
C# string insCmd = "INSERT INTO TABLE(AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)"
If you are sure about the order of columns you can skip specifying columns, this can be risky in case you screw up order of VALUES you will insert values into wrong columns
SQL Sytanx - INSERT INTO TABLE VALUES ('AccountName', 'Passphrase', 'EmailAddress', 'FullName', 'Country')
C# string insCmd = "INSERT INTO TABLE VALUES (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)"
Good resources to read would be
W3School - http://www.w3schools.com/sql/sql_insert.asp
Technet - http://technet.microsoft.com/en-us/library/dd776381(v=sql.105).aspx
Alternative to INSERT INTO TABLE you can call stored procedures from C# that inserts into table. Use of stored procedures can help you reduce ad-hoc queries, help prevent SQL injection, reduce network traffic, add additional validation server side. Your code will look as follows.
SqlCommand cmd = new SqlCommand("usp_InsertIntoAccount", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#AccountName", TextBoxUN.Text));
cmd.Parameters.Add(new SqlParameter("#Passphrase", TextBoxPass.Text));
cmd.Parameters.Add(new SqlParameter("#EmailAddress", TextBoxEA.Text));
cmd.Parameters.Add(new SqlParameter("#FullName", TextBoxFN.Text));
cmd.Parameters.Add(new SqlParameter("#Country", DropDownListCountry.SelectedItem.ToString()));
try
{
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch(Exception er)
{
Response.Write("<b>Something Really Bad Happened... Please Try Again.< /br></b>");
Response.Write(er.Message);
}
Additional resources are listed on answer at the following questions How to execute a stored procedure within C# program
I'm using Visual C# connected to MySQL for study purposes and I'm stuck in throwing an error to the user when he types a username that already exists.
Current code to put things into the database (it may be useless, once my question may be much more about SQL):
s = new sql(); // This calls a class that works as an adapter to connect form with the database
Conn = s.Connection;
Conn.Open();
coma = Conn.CreateCommand();
coma.CommandText = "INSERT INTO test.test (`user`,`password`) VALUES ('"+username.Text+"','"+password.Text+"');";
coma.ExecuteNonQuery();
What I want to do it compare "username.Text" ("username" is a TextBox) with the values on database's "test" table and, if some value match, evoke a MessageBox.Show("Hey guy, this username is already in use! Try something different)
Some points about your code sample
You want to be sure that you dispose of your connection and command objects. For my answer, I've wrapped them in using statements which will take care of that for me.
You do not want to go to the database with unsanitized inputs. I am going to use parameterized queries in the example.
It's not a good idea to store passwords in plain text. I am not going to demonstrate more secure techniques, just know to look for information about encrypting passwords, salt keys, etc.
And now for some code. In this, I'm using OleDb objects, retrofit to your particular database. And, of course, provide appropriate names to tables, columns, etc.
using (OleDbConnection connection = SomeMethodReturningConnection())
using (OleDbCommand command = SomeMethodReturningCommand())
{
command.Parameters.Add(new OleDbParameter("#username", username));
command.CommandText = "Select Count(*) From Users where Username = #username";
connection.Open();
int output = (int)command.ExecuteScalar();
if (output > 0)
{
// username already exists, provide appropriate action
}
else
{
// perform insert
// note: #username parameter already exists, do not need to add again
command.Parameters.Add(new OleDbParameter("#password", password));
command.CommandText = "Insert Into Users (Username, Password) Values (#username, #password)";
command.ExecuteNonQuery();
}
}
Thank you Anthony! Your answer put me on the right track. Although there is something that the people who will read this post should change from your code in order to get it working with Odbc connectors: the way as parameters are parsed and the way as the textbox content is extracted:
using (OdbcConnection connection = SomeMethodReturningConnection())
using (OdbcCommand command = SomeMethodReturningCommand())
{
command.Parameters.Add(new OdbcParameter("#username", username.Text));
command.CommandText = "Select Count(*) From Users where Username = ?";
connection.Open();
int output = (int)command.ExecuteScalar();
if (output > 0)
{
// username already exists, provide appropriate action
}
else
{
// perform insert
// note: #username parameter already exists, do not need to add again
command.Parameters.Add(new OdbcParameter("#password", password.Text));
command.CommandText = "Insert Into Users (Username, Password) Values (?,?)**";
command.ExecuteNonQuery();
}
}
Thank you anyway!
I have problems inserting a textboxvalue into a mysql database - there's no errormessage and no inserting. What am I doing wrong
private void RegisterCustomer()
{
string firstname = txtfirstname.ToString();
OdbcConnection conn;
conn = new OdbcConnection(ConfigurationManager.ConnectionStrings["jConnString"].ConnectionString);
conn.Open();
string sql = "insert into klant (firstname) values (#firstname)";
OdbcCommand cmd = new OdbcCommand(sql, conn);
cmd.Parameters.Add("#firstname", OdbcType.VarChar).Value = firstname;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Check.Text += ex.ToString() + sql;
}
finally
{
conn.Close();
conn.Dispose();
Check.Text += "OK";
}
}
According to MSDN.
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbccommand.parameters.aspx
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.
So your query should be:
string sql = "insert into klant (firstname) values (?)"
If you have multiple parameters, they are set in the order you add them.
In addition, I think the line
string firstname = txtfirstname.ToString();
should read
string firstname = txtfirstname.Text();
But that is not what is causing your immediate problem.
"insert into klant values (firstname) values (#firstname)"
I think the right query would be:
"insert into klant values (#firstname)";
Your query:
string sql = "insert into klant values (firstname) values (#firstname)";
Is specifying values twice. It should be in the form:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
So remove the extra values and you should be good.
You have values twice. I've never seen it that way. You INSERT INTO table (columm_names...) VALUES (value1, 'value2',...)
edit: maybe you should try straight text and eliminate the box to see if it enters. At least you'll know where to look.
edit: I'd also echo my firstname variable to see what it has.
More accurately, it should be:
insert into klant (firstname) values (#firstname)
well, the question is clear i hope, the code is this:
string sql = "delete from #tabelnaam";
SqlCommand sc = new SqlCommand();
sc.Connection = getConnection();
sc.CommandType = CommandType.Text;
sc.CommandText = sql;
SqlParameter param = new SqlParameter();
param.Direction = ParameterDirection.Input;
param.ParameterName = "#tabelnaam";
param.Value = tableName;
sc.Parameters.Add(param);
OpenConnection(sc);
sc.ExecuteScalar();
tableName is supplied to this function.
I get the exception:
Must declare the table variable #tabelnaam
IIRC, you cant use a substitute the table name for a parameter.
Rather build the SQL string containing the correct table name.
Make to changes
rather than using paramter use this
string sql = string.format( "delete from {0}",tableName);
make use of executenonquery intead of ExecuteScalar
sc.ExecuteNonQuery();
As mentioned by others, you can't parameterise the table name.
However, as you rightly mention in comments on other answers, using simple string manipulation potentialy introduces a SQL injection risk:
If your table name input is fro an untrusted source, such as user input, then using this:
string sql = string.format( "DELETE FROM {0}",tableName);
leaves you open to the table name "myTable; DROP DATABASE MyDb" being inserted, to give you:
DELETE FROM myDb; DROP DATABASE MyDB
The way round this is to delimit the table name doing something such as this:
string sql = string.format("DELETE FROM dbo.[{0}]", tableName);
in combination with checking that the input does not contain either '[' or ']'; you should probably check it also doesn't contain any other characters that can't be used as a table name, such as period and quotes.
I dont think you can parameterize the table name. From what I have read you can do it via Dynamic sql and calling sp_ExecuteSQL.
Your SQL is incorrect, you are deleting from a table variable yet you haven't defined that variable.
Update: as someone has pointed out, you are trying to dynamically build a query string but have inadvertantly used SQL parameters (these do not act as place holders for string literals).
More here:
Parameterise table name in .NET/SQL?
You cannot parameterise the table name, you have to inject it into the command text.
What you can and should do is protect yourself against SQL injection by delimiting the name thus:
public static string Delimit(string name) {
return "[" + name.Replace("]", "]]") + "]";
}
// Construct the command...
sc.CommandType = CommandType.Text;
sc.CommandText = "delete from " + Delimit(tableName);
sc.ExecuteNonQuery();
See here and here for more background info.