System.Data.SqlClient.SqlException: 'Incorrect syntax near '('.' - c#

I am trying to insert data into my database. I can't find any reason why my affectedResults are 0 and it keeps crashing out giving me a big squiggly on my cmd.ExecuteNonQuery(), it says there is a 'Incorrect syntax near '('.' so I have carefully analyzed my sql statement for the past hour and i'm not too sure where the problem is.
private int SendData(string sqlStatement)
{
SqlConnection conn = new SqlConnection(Properties.Settings.Default.cnnString);
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
int AffectedRecords = 0;
using (conn)
{
conn.Open();
AffectedRecords = cmd.ExecuteNonQuery();
conn.Close();
}
return AffectedRecords;
}
private void InsertData()
{
string sql = string.Format("INSERT INTO Participant (LastName, FirstName, " + ("Country, Gender, IACMember, Rank, SponsorId" +
"VALUES (\'{0}\',\'{1}\',\'{2}\',\'{3}\','{4}',{5}, {6})"),
txtLastName.Text, txtFirstName.Text, cboCountry.SelectedItem, Gender(gender),
(chkMember.Checked), ((txtRank.Text == string.Empty) ? "Null" : txtRank.Text),
((cboSponsor.Text == "No Sponsor") ? "Null" : cboSponsor.SelectedValue));
SendData(sql);
}

Why don't you insert data the simple way? Also you are exposing yourself to SQL INJECTIONS. Here is the Method
private int InsertData()
{
int AffectedRecords = 0;
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.cnnString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Participant (LastName, FirstName, Country, Gender, IACMember, Rank, SponsorId) VALUES (#LastName, #FirstName, #Country, #Gender, #IACMember, #Rank, #SponsorId)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cboCountry.SelectedItem);
//Your Remaining Fields
AffectedRecords = cmd.ExecuteNonQuery();
}
}
return AffectedRecords;
}

Related

The commandText property is not properly initialized

I'm trying to implement data into 2 (later on 3) tables simultaneously using a C# console application. I want to implement into table 'user' a firstname, lastname and userID, user ID will be auto incremented.
That same userID should also be implemented into table 'profile' along with a porilfeID (once again, done autoamtically by auto increment) and a profileName.
But somewhere it throws the error of commandtext not properly initialized and I cant figure out anymore what I am doing wrong.
class SQLCreate
{
public void create(int entries)
{
string ConnectionString = "server=localhost;uid=root;pwd=;database=databaseassignment;";
MySqlConnection conn;
MySqlCommand cmd;
MySqlDataAdapter adapter;
conn = new MySqlConnection();
int entryValue = entries;
conn.ConnectionString = ConnectionString;
try
{
Stopwatch stopw = new Stopwatch();
stopw.Start();
conn.Open();
cmd = new MySqlCommand();
adapter = new MySqlDataAdapter();
cmd.Connection = conn;
for (int i = 0; i < entryValue; i++)
{
MySqlCommand cmd1 = new MySqlCommand("INSERT INTO user (firstName, lastName) VALUES (#firstName, #lastName)", conn);
//MySqlCommand cmd1 = new MySqlCommand("INSERT INTO user (firstName, lastName) VALUES (#firstName, #lastName)", conn);
cmd1.Parameters.AddWithValue("#firstName", "John");
cmd1.Parameters.AddWithValue("#lastName", "Doe");
cmd1.CommandType = CommandType.Text;
int userId = Convert.ToInt32(cmd1.ExecuteScalar());
MySqlCommand cmd2 = new MySqlCommand("INSERT INTO profile (userId, profileName) VALUES (#userId, #profileName)", conn);
cmd2.Parameters.AddWithValue("#userId", userId);
cmd2.Parameters.AddWithValue("#profileName", "John Doe");
cmd2.CommandType = CommandType.Text;
cmd2.ExecuteNonQuery();
string firstName = Faker.Name.First();
string lastName = Faker.Name.Last();
string profileName = Faker.Name.First();
cmd.Parameters.Add("#firstName", MySqlDbType.String);
cmd.Parameters["#firstName"].Value = firstName;
cmd.Parameters.Add("#lastName", MySqlDbType.String);
cmd.Parameters["#lastName"].Value = lastName;
cmd.Parameters.Add("#profileName", MySqlDbType.String);
cmd.Parameters["#profileName"].Value = profileName;
cmd.ExecuteNonQuery();
}
conn.Close();
stopw.Stop();
Console.WriteLine(" Time elapsed: {0} ", stopw.Elapsed);
} catch (MySql.Data.MySqlClient.MySqlException ex) {
Console.WriteLine(ex.Message);
}
}
}
}
You create cmd = new MySqlCommand(); but never set its .CommandText property. Calling cmd.ExecuteNonQuery(); will fail because there's no CommandText to execute.
Either set cmd.CommandText or change the constructor to cmd = new MySqlCommand("text here", conn);.

Execute Reader: Connection Property has not been initialized in C# and Visual Studio

I keep getting the error
ExecuteReader: Connection Property has not been initialized
in C# and Visual Studio. I have tried some solutions that I researched but they do not seem to be doing the trick.
Here is my code:
public static int AddCustomer(Customer customer)
{
MySqlConnection connection = MySqlCommand.GetConnection();
string strInsertStatement =
"INSERT Customers (Name, Address, City, State, ZipCode) " +
"VALUES (#Name, #Address, #City, #State, #ZipCode)";
MySql.Data.MySqlClient.MySqlCommand insertCommand = new MySql.Data.MySqlClient.MySqlCommand(strInsertStatement);
insertCommand.Parameters.AddWithValue("#Name", customer.strFirstName);
insertCommand.Parameters.AddWithValue("#Address", customer.strStreetName);
insertCommand.Parameters.AddWithValue("#City", customer.strCity);
insertCommand.Parameters.AddWithValue("#State", customer.strState);
insertCommand.Parameters.AddWithValue("#ZipCode", customer.strPhoneNumber);
try
{
connection.Open();
insertCommand.ExecuteNonQuery();
string strSelectStatement = "SELECT IDENT_CURRENT('Customers') FROM Customers";
MySql.Data.MySqlClient.MySqlCommand selectCommand = new MySql.Data.MySqlClient.MySqlCommand(strSelectStatement, connection);
int customerID = Convert.ToInt32(selectCommand.ExecuteScalar());
return customerID;
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
What am I missing that is making this error appear?
The error says it all: Connection Property has not been set.
You have a Connection, and you have insertCommand. Nowhere in the code are you telling insertCommand to use the Connection.
insertCommand.Connection = connection;
Or, possibly, as part of its connector as you do with the Select.
You have to give the connection as second parameter to MySQlCommand:
MySql.Data.MySqlClient.MySqlCommand insertCommand =
new MySql.Data.MySqlClient.MySqlCommand(strInsertStatement, connection);
You need to set the Connection property of the command. Use the constructor that accepts a MySqlConnection.
MySql.Data.MySqlClient.MySqlCommand insertCommand = new MySql.Data.MySqlClient.MySqlCommand(strInsertStatement, connection);
In which line do you get the error? I just had a quick look at your code and think you forgot to add your connection to the insert command use the following instead:
EDIT: Put all the code here and added printing of error to console and assignment of connection.
I guess you get your error in the open() method call. There is no connect string in your solution. Don't forget to enter your credentials.
public static int AddCustomer(Customer customer)
{
MySqlConnection connection = new MySqlConnection();
connection.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;"
string strInsertStatement =
"INSERT Customers " +
"(Name, Address, City, State, ZipCode) " +
"VALUES (#Name, #Address, #City, #State, #ZipCode)";
MySql.Data.MySqlClient.MySqlCommand insertCommand =
new MySql.Data.MySqlClient.MySqlCommand(strInsertStatement);
insertCommand.Parameters.AddWithValue(
"#Name", customer.strFirstName);
insertCommand.Parameters.AddWithValue(
"#Address", customer.strStreetName);
insertCommand.Parameters.AddWithValue(
"#City", customer.strCity);
insertCommand.Parameters.AddWithValue(
"#State", customer.strState);
insertCommand.Parameters.AddWithValue(
"#ZipCode", customer.strPhoneNumber);
try
{
connection.Open();
insertCommand.Connection = connection;
insertCommand.ExecuteNonQuery();
string strSelectStatement =
"SELECT IDENT_CURRENT('Customers') FROM Customers";
MySql.Data.MySqlClient.MySqlCommand selectCommand =
new MySql.Data.MySqlClient.MySqlCommand(strSelectStatement, connection);
int customerID = Convert.ToInt32(selectCommand.ExecuteScalar());
return customerID;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
throw ex;
}
finally
{
connection.Close();
}
}

Incorrect syntax near 'achternaam'

I am trying to insert a new row into a SQL Server table from a Winforms application. As far as I know my query is correct but Visual Studio keeps returning an error:
Incorrect syntax near 'achternaam'
I hope that someone can point me in the right direction.
public void UpdateGegevens(int id, string voornaam, string achternaam, string functie, DateTime geboortedatum, decimal uurloon)
{
if (ReturnFirstTime(id) == true)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tbl_Gegevens (Id, voornaam, achternaam, geboortedatum, functie, uurloon) VALUES (#Id, #vn, #an, #gb, #f, #ul);";
command.Parameters.Add("#Id", SqlDbType.Int).Value = id;
command.Parameters.Add("#vn", SqlDbType.VarChar).Value = voornaam;
command.Parameters.Add("#an", SqlDbType.VarChar).Value = achternaam;
command.Parameters.Add("#f", SqlDbType.VarChar).Value = functie;
command.Parameters.Add("#gb", SqlDbType.Date).Value = geboortedatum;
command.Parameters.Add("#ul", SqlDbType.Money).Value = uurloon;
try
{
con.Open();
command.ExecuteScalar();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
else
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE tbl_Gegevens SET voornaam=#vn achternaam=#an geboortedatum=#gb funtie=#f uurloon=#ul WHERE Id = #Id;";
command.Parameters.AddWithValue("#Id", id);
command.Parameters.AddWithValue("#vn", voornaam);
command.Parameters.AddWithValue("#an", achternaam);
command.Parameters.AddWithValue("#gb", geboortedatum);
command.Parameters.AddWithValue("#f", functie);
command.Parameters.AddWithValue("#ul", uurloon);
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
Here is a specification of tbl_Gegevens:
create table [dbo].[tbl_Gegevens] (
[Id] int not null
, [voornaam] nvarchar(50) null
, [achternaam] nvarchar(50) null
, [geboortedatum] date null
, [functie] nvarchar(50) null
, [uurloon] smallmoney null
, primary key clustered ([Id] asc)
);
I think my dbms is ADO.Net.
This is the way i'm passing the info to the method:
private void btnConfirm_Click(object sender, EventArgs e)
{
if (tbName.Text != "" && tbSurname.Text != "" && tbFunction.Text
!= "" && dtpBirthdate.Value != date && nudSalary.Value != 0)
{
Database1.SetFirstTime(ID);
Database1.UpdateGegevens(ID, tbName.Text, tbSurname.Text, tbFunction.Text, dtpBirthdate.Value, nudSalary.Value);
this.Hide();
frmMain fm = new frmMain(ID);
fm.Show();
}
else
{
MessageBox.Show("Vul alle velden in!");
}
}
This is the query i use to get my id:
public int ReturnLoginID(string username, string password)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
int ID = 9999;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
ID = reader.GetInt32(0);
}
con.Close();
return ID;
}
In the UPDATE part of your code there are no commas to separate the fields in the SET list
command.CommandText = #"UPDATE tbl_Gegevens SET voornaam=#vn,
achternaam=#an, geboortedatum=#gb,
funtie=#f, uurloon=#ul WHERE Id = #Id;";
I think that this question could be used to underline the importance of using a debugger. This problem would be solved much sooner if you had stepped through your code using the debugger.

MySQL C# Query trouble - Updating table

I'am having trouble with this function I'm creating to Update my database. The Update faculty member seems to work perfectly while the Updating of the person tables does not . I'm presuming that the MySQL Query isn't correct for updating the person table.
Additional INFO: My code is hooked to an GUI mock as of right now for testing purposes . the Update string with #Id.. its just to select which ID I wish to change..
public static void Update(string update,string fName, string lName, string DOB, string postCode, string address, string phoneNumber,
bool isTenured, string qualifications, string previousEmployment)
{
MySqlConnection conn;
MySqlCommand cmd;
string sql = "UPDATE person SET firstName = #FirstName , lastName = #LastName, DOB = #DOB, phoneNumber = #PhoneNumber, address = #Address, postCode = #PostCode WHERE ID =#Id;";
GetConnection(out conn, out cmd, sql);
try
{
cmd.Parameters.AddWithValue("#Id", update);
cmd.Parameters.AddWithValue("#FirstName", fName);
cmd.Parameters.AddWithValue("#LastName", lName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#PhoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#Address", address);
cmd.Parameters.AddWithValue("#PostCode", postCode);
long id = (long)cmd.LastInsertedId;
sql = "UPDATE facultymember SET isTenured = #IsTenured, qualifications = #Qualifications, previousEmployment = #PreviousEmployment WHERE Person_personID=#Id";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#IsTenured", isTenured);
cmd.Parameters.AddWithValue("#Qualifications", qualifications);
cmd.Parameters.AddWithValue("#PreviousEmployment", previousEmployment);
cmd.ExecuteNonQuery();
}
catch (NullReferenceException nre)
{
MessageBox.Show(nre.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
try
{
MessageBox.Show("Updated");
cmd.Connection.Close();
conn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
You forget to add #Id parameter in your second sql query.
sql = "UPDATE facultymember
SET isTenured = #IsTenured, qualifications = #Qualifications, previousEmployment = #PreviousEmployment
WHERE Person_personID=#Id";
// ^^^^
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#IsTenured", isTenured);
cmd.Parameters.AddWithValue("#Qualifications", qualifications);
cmd.Parameters.AddWithValue("#PreviousEmployment", previousEmployment);
cmd.Parameters.AddWithValue("#Id", YourIdValue);
cmd.ExecuteNonQuery();
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(ConnectionString))
using(MySqlCommand cmd = conn.CreateCommand())
{
//
}

SQL Server error: ExecuteNonQuery: Connection property has not been initialized

I am trying to develop a sample registration page using ASP.Net and C#. I am calling a stored procedure to insert the data to database. My database is SQL Server 2008.
This is my code:
public partial class Sample : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
string str;
protected void Page_Load(object sender, EventArgs e)
{
rbt_Male.Checked = true;
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
string #Name = txtbx_Name.Text;
string #Gender_male = rbt_Male.Text;
string #Gender_Female = rbt_Female.Text;
string #Email = txtbx_Email.Text;
DateTime #Dob = Convert.ToDateTime(txt_Dob.Text);
submitdata();
}
protected void submitdata()
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
if (rbt_Male.Checked)
{
cmd.Parameters.AddWithValue("#Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("#Gender_Male", rbt_Male.Text);
cmd.Parameters.AddWithValue("#Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("#Dob", Convert.ToDateTime(txt_Dob.Text));
}
else if (rbt_Female.Checked)
{
cmd.Parameters.AddWithValue("#Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("#Gender_Female", rbt_Male.Text);
cmd.Parameters.AddWithValue("#Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("#Dob", Convert.ToDateTime(txt_Dob.Text));
}
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = "Record Inserted Successfully";
con.Close();
}
catch (Exception ex)
{
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = ex.Message;
}
I am getting the error message
ExecuteNonQuery: Connection property has not been initialized.
I am getting this error at cmd.ExecuteNonQuery();
Please help me.
My stored procedure is
ALTER Procedure insertdata
(
#Name Varchar(20),
#Gender Varchar(6),
#Email Varchar(20),
#Dob date
)
As
Begin
Insert into samplelogintable (Name, Gender, Email, Dob)
Values(#Name, #Gender, #Email, #Dob)
End
You haven't associated your command cmd with your SqlConnection, that is why you are getting the error.
You need to specify:
cmd.Connection = con;
in your submitdata() method.
Since SqlCommand implements IDisposable, its better if you use it within using block like:
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
cmd.Connection = con;
.... your code
}

Categories

Resources