I have created a simple program to insert values into the table [regist], but I keep getting the error
Incorrect syntax near ')'
on cmd.ExecuteNonQuery();:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact, " + ") VALUES (" + " #textBox1.Text, #textBox2.Text, #textBox3.Text, #textBox4.Text, #comboBox1.Text,#comboBox2.Text,#textBox7.Text" + ")", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
I am new to this and I am really confused.
As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.
Also: I would recommend to separate the click event handler from the actual code to insert the data.
So I would rewrite your code to be something like
In your web page's code-behind file (yourpage.aspx.cs)
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
InsertData(connectionString,
textBox1.Text.Trim(), -- first name
textBox2.Text.Trim(), -- last name
textBox3.Text.Trim(), -- user name
textBox4.Text.Trim(), -- password
Convert.ToInt32(comboBox1.Text), -- age
comboBox2.Text.Trim(), -- gender
textBox7.Text.Trim() ); -- contact
}
In some other code (e.g. a databaselayer.cs):
private void InsertData(string connectionString, string firstName, string lastname, string username, string password
int Age, string gender, string contact)
{
// define INSERT query with parameters
string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FirstName, #Lastname, #Username, #Password, #Age, #Gender, #Contact) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstName;
cmd.Parameters.Add("#Lastname", SqlDbType.VarChar, 50).Value = lastName;
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 50).Value = userName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = password;
cmd.Parameters.Add("#Age", SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar, 50).Value = gender;
cmd.Parameters.Add("#Contact", SqlDbType.VarChar, 50).Value = contact;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
Code like this:
is not vulnerable to SQL injection attacks
performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)
Remove the comma
... Gender,Contact, " + ") VALUES ...
^-----------------here
Following Code will work for "Inserting values into a SQL Server database using ado.net via C#"
// Your Connection string
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
// Collecting Values
string firstName="Name",
lastName="LastName",
userName="UserName",
password="123",
gender="Male",
contact="Contact";
int age=26;
// Query to be executed
string query = "Insert Into dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FN, #LN, #UN, #Pass, #Age, #Gender, #Contact) ";
// instance connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// add parameters and their values
cmd.Parameters.Add("#FN", System.Data.SqlDbType.NVarChar, 100).Value = firstName;
cmd.Parameters.Add("#LN", System.Data.SqlDbType.NVarChar, 100).Value = lastName;
cmd.Parameters.Add("#UN", System.Data.SqlDbType.NVarChar, 100).Value = userName;
cmd.Parameters.Add("#Pass", System.Data.SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#Age", System.Data.SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", System.Data.SqlDbType.NVarChar, 100).Value = gender;
cmd.Parameters.Add("#Contact", System.Data.SqlDbType.NVarChar, 100).Value = contact;
// open connection, execute command and close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
you should remove last comma and as nrodic said your command is not correct.
you should change it like this :
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
DataSet ds = new DataSet("detail1");
ad.Fill(ds, "detail1");
DataRow row = ds.Tables["detail1"].NewRow();
row["Name"] = textBox1.Text;
row["address"] =textBox2.Text;
ds.Tables["detail1"].Rows.Add(row);
ad.Update(ds, "detail1");
con.Close();
MessageBox.Show("insert secussfully");
}
Related
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);.
I keep on getting the problem
"An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.dll" "on
SDA.SelectCommand.ExecuteNonQuery();".
Whats the problem here?
SqlConnection con = new SqlConnection(#"Data Source=LAPTOP-LD5OK96E\SQLEXPRESS;Initial Catalog=TRANSACTION_RATE TABLE; Integrated Security=True");
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
String query = "INSERT INTO TRANSACTION_RATE TABLE (Trans_id,Transaction_type,Transact_rate,Transact_description) VALUES('" + textBox1.Text + "','" + textBox2.Text + "''" + textBox3.Text + "''" + textBox4.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("Success!");
You have one stray TABLE keyword after your table's name, you need to remove it. as a second note, you need to be aware that this kind of string concatenation is avoided and it is open to SQL Injection attack:
String query = "INSERT INTO TRANSACTION_RATE (Trans_id,Transaction_type,Transact_rate,Transact_description) VALUES (#Trans_id, #Transaction_type,#Transact_rate, #Transact_description)";
SDA.SelectCommand.Parameters.Add("#Trans_id", SqlDbType.NVarChar, 50).Value = textBox1.Text;
SDA.SelectCommand.Parameters.Add("#Transaction_type", SqlDbType.NVarChar, 50).Value = textBox2.Text;
SDA.SelectCommand.Parameters.Add("#Transact_rate", SqlDbType.NVarChar, 50).Value = textBox3.Text;
SDA.SelectCommand.Parameters.Add("#Transact_description", SqlDbType.NVarChar, 50).Value = textBox4.Text;
In case your table was named in fact TRANSACTION_RATE TABLE you should escape the name like this:
INSERT INTO [TRANSACTION_RATE TABLE] ....
I've been trying to write to a database and save to the file but I cant get it to work, can't tell why either.
The error I get is:
Exception thrown: 'System.Data.OleDb.OleDbException' in System.Data.dll
Additional information:
Could not find installable ISAM.
Here's the Code I'm running, any help/advice would be greatly appreciated
private void BtnSubmit_Click(object sender, EventArgs e)
{
OleDbConnection Conn = new OleDbConnection();
Conn.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =| DataDirectory |\\HoliPlanData.accdb; Trusted_Connection = True;";
String PayrollNo = TxtPayroll.Text;
String FirstName = TxtFirstName.Text;
String LastName = TxtLastName.Text;
String AnnualHolidayEntitlemet = TxtAHE.Text;
String DaysTakenToDate = TxtDTTD.Text;
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate");
Query.Connection = Conn;
Conn.Open(); //THIS IS WHERE THE ERROR OCCURS IN CODEPROSSESS
if (Conn.State == ConnectionState.Open)
{
Query.Parameters.Add("#PayrollNo", OleDbType.VarChar).Value = PayrollNo;
Query.Parameters.Add("#FirstName", OleDbType.VarChar).Value = FirstName;
Query.Parameters.Add("#LastName", OleDbType.VarChar).Value = LastName;
Query.Parameters.Add("#AnnualHolidayEntitlement", OleDbType.VarChar).Value = AnnualHolidayEntitlemet;
Query.Parameters.Add("#DaysTakenToDate", OleDbType.VarChar).Value = DaysTakenToDate;
try
{
Query.ExecuteNonQuery();
MessageBox.Show("Data Added Successfully");
Conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
Conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
Two issues:
Your connection string has an extra semicolon as you pointed out in comments above
Your INSERT query is missing the last parenthesis )
Compare these lines:
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate");
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate)");
Install AccessDatabaseEngine and try again.
Change the connection string as below.
Conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\\HoliPlanData.accdb;Trusted_Connection = True;";
I keep getting a username is incorrect error this is for login i dont know why i desperatley need help, i did everything correct but still gives me errors what can i do
below is my code
protected void Button_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from [Table] where UserName=#UserName";
SqlCommand com = new SqlCommand(checkuser, conn);
com.Parameters.Add("#UserName", SqlDbType.NChar, 20).Value = TextBoxUserName.Text + "'";
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
//int temp = Convert.ToInt32(com.ExecuteScalar());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = " select password from [Table] where UserName=#UserName";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
passComm.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = TextBoxUserName.Text;
string password = passComm.ExecuteScalar().ToString().Replace(" ", "");
if (password == TextBoxPassword.Text)
{
//declaring new session
Session["New"] = TextBoxUserName.Text;
Response.Write("PASSWORD IS CORRECT");
Response.Redirect("Default.aspx");
}
else
{
Response.Write("PASSWORD IS NOT CORRECT");
}
}
else
{
Response.Write("USERNAME IS NOT CORRECT");
}
}
You don't need to add single quote at the end of the username.
Replace This:
com.Parameters.Add("#UserName", SqlDbType.NChar, 20).Value =
TextBoxUserName.Text + "'";
^^^^^^
With This:
com.Parameters.Add("#UserName", SqlDbType.NChar, 20).Value = TextBoxUserName.Text;
You should also trim your parameters in both queries.
string checkPasswordQuery = " select password from [Table] where Ltrim(Rtrim(UserName))=#UserName";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
passComm.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = TextBoxUserName.Text.Trim();
Your SQL query is case-sensitive, which may or may not be intended.
You believe you can use
"select count(*) from [Table] where Lower(UserName)=Lower(#UserName)"
MDSN Link: http://msdn.microsoft.com/en-us/library/ms174400.aspx
SqlConnection con = new SqlConnection("Data Source=RANJEETMAURYA;Initial Catalog=Project;Integrated Security=True");
con.Open();
DateTime current = DateTime.Now;
//DateTime CurrentDate;
//CurrentDate = Convert.ToDateTime(DateTime.Now.ToString("dd-MMM-yyyy"));
current = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy hh:mm"));
SqlCommand cmd = new SqlCommand(#"INSERT INTO CustomerDetails
(Date, Name, Gender, Address, Contact_No, Email_ID)
VALUES ('" +current+ "','" + txtName.Text + "','" + Gender + "','" + txtAddress.Text + "','" + txtContact.Text + "','" + txtEmail.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Customer Information Added Successfully.", "Dairy Management System", MessageBoxButtons.OK, MessageBoxIcon.Information);
SQLFunctions.Refresh(this.dataGridCustomerDetails);
this is the error please help me out
for what reason it is running some times, it is not running some times.
System.FormatException was unhandled
HResult=-2146233033
Message=String was not recognized as a valid DateTime.
Source=mscorlib
StackTrace:
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.Convert.ToDateTime(String value)
at IndianDiary.frmCustomerDetails.btnAddNew_Click(Object sender, EventArgs e) in
You are converting current time to string and then parsing string back to DateTime:
DateTime current = DateTime.Now;
current = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy hh:mm"));
What is the point of this? Just use DateTime.Now. Also use command parameters.
string sql = #"INSERT INTO CustomerDetails
(Date, Name, Gender, Address, Contact_No, Email_ID)
VALUES (#date, #name, #gender, #address, #contactNo, #emailId)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#gender", Gender);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#contactNo", txtContact.Text);
cmd.Parameters.AddWithValue("#emailId", txtEmail.Text);
See How does SQLParameter prevent SQL Injection?
Also use App.config to store connection string:
<connectionStrings>
<add name="ranjeet"
connectionString="Data Source=RANJEETMAURYA;Initial Catalog=Project;Integrated Security=True"
providerName="System.Data.EntityClient" />
</connectionStrings>
Then you will be able to get it with ConfigurationManager.
Also wrap connection and command into using statement to dispose them automatically:
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
// add parameters
con.Open();
cmd.ExecuteNonQuery();
}
Why are You converting it to string just send DateTime.Now to database and while retrieving it from database use this
retrievedDate= DateRetrieved.ToString("MM/dd/yyyy hh:mm");
As Reference to the answer of Sergey Berezovskiy
you can also pass the parameter as:
string sql = #"INSERT INTO CustomerDetails
(Date, Name, Gender, Address, Contact_No, Email_ID)
VALUES (#date, #name, #gender, #address, #contactNo, #emailId)";
SqlCommand cmd = new SqlCommand(sql);
cmd.Parameters.Add("#date", SqlDbType.Date).Value = DateTime.Now;
cmd.Parameters.Add("#name", SqlDbType.Varchar, 50).Value = txtName.Text;
cmd.Parameters.Add("#gender", SqlDbType.Varchar, 10).Value = Gender;
cmd.Parameters.Add("#address", SqlDbType.Varchar, 50).Value =txtAddress.Text;
cmd.Parameters.Add("#contactNo", SqlDbType.Varchar, 25).Value = txtContact.Text;
cmd.Parameters.Add("#emailId", SqlDbType.Varchar, 35).Value =txtEmail.Text;