I get syntax error when using 'Insert into' SQL command using c#. I'm using Access db to store some data.
Surprisingly, when I copy the exact command into MS Access to try if it's not correct, it works like charm. I'm a bit confused! I appreciate any idea or help in this regard. Here is my code:
using (OleDbConnection connection = new OleDbConnection(Global.ConString))
{
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO Users(Name,UserName,Password,Customers,Jobs,Invoice,Statement,Reports,Users) values (#name,#UserName,#Password,#Customers,#Jobs,#Invoice,#Statement,#Reports,#Users)";
command.Parameters.AddWithValue("#name",fullName.Text );
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", passWord.Text);
command.Parameters.AddWithValue("#Customers", Customers.Checked);
command.Parameters.AddWithValue("#Jobs", Jobs.Checked);
command.Parameters.AddWithValue("#Invoice", Invoice.Checked);
command.Parameters.AddWithValue("#Statement", Statement.Checked);
command.Parameters.AddWithValue("#Reports", Report.Checked);
command.Parameters.AddWithValue("#Users", userDef.Checked);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
if (recordsAffected > 0)
{
foreach (Control item in newRecord.Controls)
{
if (item is TextBox) item.ResetText();
}
timer1.Enabled = true;
}
else
MessageBox.Show("Insert Fail");
}
catch (OleDbException err)
{
MessageBox.Show("Somthing wrong. Error no. is: " + err.ErrorCode + "..." + err.Message);
}
}
}
Most likely your issue is the use of a reserved word as an identifier, specifically 'Password'. Wrap that column name in brackets, i.e. [Password] and you should be good to go.
It's best to avoid reserved words if possible. Generally speaking, you should not be storing unhashed passwords in your database so a column name like 'PasswordHash` is appropriate and avoids this issue.
Related
As a beginner to c#, and I actaully spent a lot of time researching this:
I cannot add some data into the database, I can extract data from it, but cannot add anything into the database. I use sql server as my database.
try {
fname = fname_tb.Text;// first name
sname = sname_tb.Text; // second name
q = "insert into beforebath1(firstname,secondname) values(#fname,#sname)";
conn_string = Properties.Settings.Default.beforebath_connection_string;
SqlConnection co = new SqlConnection(conn_string);
SqlCommand cmd;
co.Open();
cmd = new SqlCommand(q, co);
cmd.Connection = co;
cmd.Parameters.AddWithValue("#fname", fname_tb.Text);
cmd.Parameters.AddWithValue("#sname", sname_tb.Text);
cmd.ExecuteNonQuery();
co.Close();
}
catch(Exception err) {
MessageBox.Show(err.toString());
}
my sql connection string is this:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\beforebath_db.mdf;Integrated Security=True;Connect Timeout=30
It is automatically generated when I created the database. Please help me insert the text in the two textboxes (fname_tb.Text and sname_tb.Text) into the table called beforebath1 of the database called beforebath_db.mdf.
Is it something to do with my data directory?
I see a couple of mistakes in your code.
First, why catch an exception that will only be shown in a message?
It is often best to let the exception bubble up to have the stack trace in debug. This is not the same if this is production code, which I doubt.
Second, make sure to dispose your objects adequately.
The Using Statement is the most prefered way to work with disposeable items such as a database connection and a command.
using (var cnx = new SqlConnection(connectionString)) {
cnx.Open();
var sql = #"insert into beforebath1 (first_name, second_name)
values (#fname, #lname)";
using (var cmd = new SqlCommand(sql, cnx)) {
cmd.Parameters.AddWithValue("#fname", fname_tb.Text);
cmd.Parameters.AddWithValue("#lname", lname_tb.Text);
try {
int rowsAffected = cmd.ExecuteNonQuery();
if (0 < rowsAffected) MessageBox.Show("Success!");
else MessageBox.Show("Failed!");
} catch (SqlException ex) {
// It is almost prefered to let the exception be thrown freely
// so that you may have its full stack trace and have more
// details on your error.
MessageBox.Show(ex.Message);
} finally {
if (cnx.State == ConnectionState.Open) cnx.Close();
}
}
}
This way, wrapping your disposable objects within using blocks, you make sure that everything is getting to get disposed automatically when exiting the code block.
As for your "it doesn't work" problem, I guess the problem be either at the connection string level, or at your table_name level.
You wish to insert into beforebath1, and your insert statement states table_name. Make sure you put the right table name where it belongs so that it may work properly.
Can you change you connection string to this:
Server=(LocalDB)\v11.0;Database=beforebath_db;Trusted_Connection=True;
This means the your app and other programs using the Db will all share the same instance.
Also, as mentioned by #Will, you should wrap your SQLConnection in a using statement for garbage collection.
For better implementations you can use stored_procedures like bellow:
Step1: Declare Stored Procedure for your Query:
CREATE PROCEDURE [dbo].[ADD_TO_BEFORE_PATH_SP]
/*Type of this variables should be their column types*/
#fname varchar(MAX),
#lname varchar(MAX)
AS
BEGIN
INSERT INTO [dbo].[beforebath1] (fname, lname)
VALUES (#fname,#lname)
END
Step2: Using Stored Procedure where you need:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand("ADD_TO_BEFORE_PATH_SP", con);
com.Parameters.AddWithValue("#fname", fname_tb.Text);
com.Parameters.AddWithValue("#lname", lname_tb.Text);
com.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
I've been trying to add a row to my SQL CE & nothing works I've tried many things I found here at SO or in other websites by googling but to no avail.
Below if the code I have at the moment.
It compiles and executes with no problem, but nothing is added to the table and no exception is thrown.
Could anyone please provide a solution for this ?
string conString = Properties.Settings.Default.TestConnectionString;
using (SqlCeConnection connect = new SqlCeConnection(conString))
{
connect.Open();
string text = "UsernameTest";
string pass = "PasswordTest";
using (SqlCeCommand command = new SqlCeCommand("insert into MyTable values (#Username, #Password)", connect))
{
command.Parameters.AddWithValue("#Username", text);
command.Parameters.AddWithValue("#Password", pass);
command.ExecuteNonQuery();
}
}
Please do not comment about storing a password in plain text, this was just a test.
I'm trying to use a function via a SQL connection I've done everywhere else in my application (only here it give the error, not the rest of the application). When i searched for what that error code meant the responses i found say it's an error when one can't connect to SQL server? but it doesn't give a solution.
here is my c# code
SqlConnection connection = Database.GetConnection();
DataTable dt = new DataTable("CRC");
SqlCommand cmd = new SqlCommand("SELECT dbo.CalcRentalCharge(#RentalStartDateTime,#RentalEndDateTime,#CarTypeID)", connection);
try
{
connection.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
cmd.Parameters.Add("#RentalEndDateTimetext", SqlDbType.DateTime).Value = RentalEndDateTimeBox.Text;
cmd.Parameters.Add("#CarTypeIDtext", SqlDbType.Int).Value = CarTypeID.Text;
connection.Open();
Decimal rentalChange = (Decimal)cmd.ExecuteScalar();
connection.Close();
MessageBox.Show("The rental change is: " + rentalChange.ToString());
if (dr.HasRows)
{
dt.Load(dr);
dataGridView1.DataSource = dt;
}
}
connection.Close();
Can you help me get this FUNCTION to work?
Don't use cmd.ExecuteReader() before adding parameter to command object.
It gives error,
add parameter to command and then cmd.execureReader()
You have a copy/paste error in your variable name:
In the line
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
the string
RentalStartDateTimetext
needs to be
RentalStartDateTime
In addition to that, because it will pop up as your next error: Your opening and closing of the connection is wrong. Use a using block for the connection as well and open it directly after the start of the block. You don't need to close it manually, the using-block will do that for you.
I'm trying to upgrade the db from users' input, but it doesn't work...
I'm using this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
SqlCommand ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con);
ncmd.Parameters.AddWithValue("#vem", Session["[Indirizzo E-Mail]"].ToString());
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
ncmd.Connection = con;
con.Open();
ncmd.ExecuteNonQuery();
con.Close();
Label2.Text = "Dati aggiornati con successo!";
Response.Redirect("~/ModificaDati.aspx");
}
When I click on the button it show me the Label2 text, but in the database the "Nome" is not changed, why?
Thanks before for the answers ^^
I would change your method as below
if (Session["[Indirizzo E-Mail]"] != null &&
!string.IsNullOrEmpty(Session["[Indirizzo E-Mail]"].ToString()) &&
!string.IsNullOrEmpty(TextBox2.Text))
{
string vem = Session["[Indirizzo E-Mail]"].ToString();
using (var con = new SqlConnection(strcon))
using (var ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con))
{
con.Open();
ncmd.Parameters.AddWithValue("#vem", vem);
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
int rows = ncmd.ExecuteNonQuery();
Label2.Text = rows + " Dati aggiornati con successo!";
}
}
Response.Redirect("~/ModificaDati.aspx");
Added input validation, session values can be null, better to check before you update database
when you create SqlCommand you can give the connection, no need to set it again
make sure your SQL is valid
use using statements for disposable objects like SqlConnection, SqlCommand
Your code looks ok. Just make sure you check if SQL is correct as Damith already suggested.
Another thing I’s recommend is additionally validating your parameters for data type correctness before executing the query.
Using this approach you’ll probably avoid a lot of unnecessary exceptions and also be able to provide more user friendly messages. Of course this only applies if user input is non text type
//Data Type verification
DateTime tmp;
if (!DateTime.TryParse(Label2.Text.Trim(), out tmp))
{
//Show error message that this is not a correct data type
}
Open your connection first
con.Open();
ncmd.Connection = con;
Hope it helps
I want to ask more to show data from SQL Server to WinForm using a datagrid.
I've been creating a datagrid and the stored procedure to show data is
ALTER PROC [dbo].[SP_GetData]
AS
SELECT nama , nim
FROM tabledata
and I've created the function to access the database and the stored procedure in C#
string Sp_Name = "dbo.SP_GetData";
SqlConnection SqlCon = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBMahasiswa;Data Source=.");
SqlCon.Open();
SqlCommand SqlCom = new SqlCommand(Sp_Name , SqlCon);
SqlCom.CommandType = CommandType.StoredProcedure;
List<mahasiswaData> listMahasiswa = new List<mahasiswaData>();
using (SqlDataReader sqlDataReader = SqlCom.ExecuteReader())
{
if (sqlDataReader.HasRows)
{
while (sqlDataReader.Read())
{
mahasiswaData DataMhs = new mahasiswaData();
DataMhs.Nama = sqlDataReader["Name"].ToString();
DataMhs.Umur = Convert.ToInt32(sqlDataReader["Age"]);
listMahasiswa.Add(DataMhs);
}
}
}
SqlCon.Close();
return listMahasiswa;
and finally, in the show button I add this code
dgvmahasiswa.DataSource = new MahasiswaDB().LoadMahasiswa();
Could somebody tell me where the fault is or the alternatives one?
Thank You So Much! :D
Some things to think about:
At the moment, if your code runs into exceptions, you'll leave a
SqlConnection hanging around; you've used the using pattern for your
SqlDataReader; you should extend it to all of your disposable
objects.
You are swallowing exceptions; if your query fails, the connection
cannot be made, or something else happens, you'll never really know - your function will just return null.
Is it possible for name or age to be null? Age to be non-numeric?
There's no test for any unexpected values, which you'll also never
know about.
If you don't have any records, you'll return an empty list. Is this
desired? Or would you prefer to know there were no records?
You might prefer to look at something like this:
public List<mahasiswaData> GetData(){
List<mahasiswaData> gridData = new List<mahasiswaData>();
try{
using(SqlConnection conn = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBMahasiswa;Data Source=."))
{
using(SqlCommand command = new SqlCommand())
{
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.Text = "dbo.SP_GetData";
using(SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows){
while(reader.Read())
{
object rawName = reader.GetValue(reader.GetOrdinal("Name"));
object rawAge = reader.GetValue(reader.GetOrdinal("Age"));
if(rawName == DBNull.Value || rawAge == DBNull.Value)
{
//Use logging to indicate name or age is null and continue onto the next record
continue;
}
//Use the object intializer syntax to create a mahasiswaData object inline for simplicity
gridData.Add(new mahasiswaData()
{
Nama = Convert.ToString(rawName),
Umur = Convert.ToInt32(rawAge)
});
}
}
else{
//Use logging or similar to record that there are no rows. You may also want to raise an exception if this is important.
}
}
}
}
}
catch(Exception e)
{
//Use your favourite logging implementation here to record the error. Many projects use log4Net
throw; //Throw the error - display and explain to the end user or caller that something has gone wrong!
}
return gridData;
}
Note that if you are sure that age or name will never be null then you can simplify the middle section:
while (reader.Read())
{
//Use the object intializer syntax to create a mahasiswaData object inline for simplicity
gridData.Add(new mahasiswaData()
{
Nama = reader.GetString(reader.GetOrdinal("Name")),
Umur = reader.GetInt32(reader.GetOrdinal("Age"))
});
}