winform c# Error while inserting data (DateTime) into SQL - c#

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;

Related

What is the correct way of using (INSERT SELECT FROM WHERE) query in C#?

I'm making a form on C# that inserts data in a table with a where clause, but it's not working. I think the syntax of my query is the problem but I can't solve it.
This is the one that I tried that's working, but I need an insert query with a where clause.
SqlCommand addEmp = new SqlCommand("INSERT INTO tbl_Expenses " +
"(InvestedMoney,EstimatedServingCount,MealName) " +
"VALUES (#inv, #est, #mname)", conn);
addEmp.Parameters.AddWithValue("#mname", textBox1.Text);
addEmp.Parameters.AddWithValue("#inv", textBox2.Text);
addEmp.Parameters.AddWithValue("#est", textBox3.Text);
conn.Open();
addEmp.ExecuteNonQuery();
conn.Close();
I tried this code below:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Meal" +
" ExpensesID, MealName, MealPrice, ImageName, Imageblob)" +
"SELECT ExpensesID, #mname, #mprice, #imname, #img " +
"FROM tbl_Expenses" +
"WHERE MealName = '"+textBox1.Text+"'",conn);
cmd.Parameters.AddWithValue("#mname", textBox1.Text);
cmd.Parameters.AddWithValue("#mprice", textBox4.Text);
cmd.Parameters.AddWithValue("#imname", textBox1.Text);
cmd.Parameters.Add("#img", SqlDbType.Image, photo.Length).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
But I get this error:
System.Data.SqlClient.SqlException: Incorrect syntax near '='
This section is missing a space between the lines:
"from tbl_Expenses" +
"WHERE MealName = '"
so the sql code references a table named tbl_ExpensesWHERE, gives the table an alias of MealName, and then has an out-of-place =.
But you should also already know from the use of parameters elsewhere it is NOT okay to substitute textBox1.Text into the query like that. NEVER do that. Not even once. Not even for practice/learning code!
There are some other poor practices in here, but that was the worst. Here's a better pattern:
string sql = #"
INSERT into tbl_Meal
(ExpensesID,MealName,MealPrice,ImageName,Imageblob)
SELECT
ExpensesID,#mname,#mprice,#mname,#img
FROM tbl_Expenses
WHERE MealName = #mname";
using (var conn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, conn))
{
//wild guess at column types. Use actual column types/size FROM THE DATABASE
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 30).Value = textBox1.Text;
cmd.Parameters.Add("#mprice", SQlDbType.Decimal, 18, 8).Value = textBox4.Text;
//use the size of the column here, not the length of the photo
cmd.Parameters.Add("#img", SqlDbType.Image, 8000).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
}
Instead of Parameters.AddWithValue() use Parameters.Add() and also use correct datatypes, for example EstimatedServingCount seems to be an int, but however AddWithValue can not know that:
addEmp.Parameters.Add("#mname", SqlDbType.VarChar).Value = textBox1.Text;
addEmp.Parameters.Add("#inv", SqlDbType.VarChar).Value = textBox2.Text;
addEmp.Parameters.Add("#est", SqlDbType.Int).Value = textBox3.Text;

There is an error converting date/time to string

It was working in a computer that I was using in school however when I transferred it to my personal laptop, it suddenly got an error.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Student VALUES (#stu_fname, #stu_lname, #Address, #Phone, #Email, #DateOfBirth, #UserName, #PassWord, #DateAdded)", con);
con.Open();
cmd.Parameters.AddWithValue("#stu_fname", TxtFN.Text);
cmd.Parameters.AddWithValue("#stu_lname", TxtLN.Text);
cmd.Parameters.AddWithValue("#Address", TxtAddress.Text);
cmd.Parameters.AddWithValue("#Phone", TxtPhone.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", TxtDateOfBirth.Text);
cmd.Parameters.AddWithValue("#UserName", TxtUsername.Text);
cmd.Parameters.AddWithValue("#PassWord", TxtPassword.Text);
cmd.Parameters.AddWithValue("#DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
MessageBox.Show("Success boi");
con.Close();
Try!
cmd.Parameters.AddWithValue("#DateAdded", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Or convert string to date.
DateTime dateOfbirth = DateTime.ParseExact(TxtDateOfBirth.Text, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
cmd.Parameters.AddWithValue("#DateAdded",.TxtDateOfBirth.value.ToString("yyyy-MM-dd"));//add format you want.
//Leaving it at TxtDateOfBirth.value system date and time format will be inserted

column count does match value count at row 1 C#

I do not know why I am getting this error:
C# Code:
using (MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=***;password=***;"))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO student (studentID, studentFirstName, studentLastName, studentUserName, studentPassword) VALUES (#userID, #, #FirstName, #LastName, #Username, #Password);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("#FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("#UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("#Password", textBoxPassword.Text);
connection.Open();
cmd.Connection = connection;
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
connection.Close();
}
It may due to me overlooking something.
Error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data
Additional information: Column count doesn't match value count at row 1
Format out your code and you'll see all the syntactic problems clearly:
string connectionString =
"datasource=localhost;port=3306;database=project;username=***;password=***;";
using (MySqlConnection connection = new MySqlConnection(connectionString)) {
connection.Open();
//DONE: keep sql readable
string sql =
#"INSERT INTO student (
studentID,
studentFirstName,
studentLastName,
studentUserName,
studentPassword)
VALUES (
#userID,
#FirstName, -- wrong # param
#LastName,
#Username,
#Password);";
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(sql)) {
cmd.CommandType = CommandType.Text; // redundant
cmd.Connection = connection;
//DONE: separate code with new lines
// wrong parameter name
cmd.Parameters.AddWithValue("#userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("#FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("#UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("#Password", textBoxPassword.Text);
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Saved");
You are adding an additional parameter in your values clause (#userID, #,
also add the "#" before user id
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
should be
cmd.Parameters.AddWithValue("#userID", Convert.ToInt32(textBoxUserID.Text));

Update table values using cmd.Parameters.AddWithValue not working

I have to update some values in table row if UserId = Session["username"]
but its showing error:
ExecuteNonQuery: Connection property has not been initialized.
can any one know what i am doing wrong here a Session["username"] have its value i have checked.
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration (FirstName,LastName,Password,LastName,EmaildId,UserId) " +
"VALUES (#FirstName, #LastName, #Password, #EmaildId, #UserId) WHERE UserId='" + Session["username"] + "'";
var cmd = new SqlCommand(qry);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
You need to tell the SqlCommand-object which connection to use, change this line
var cmd = new SqlCommand(qry, conn7);
Two Problems
In SQLCOMMAND you should specify querystring,connection
Your update query syntax is wrong
..try below
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration
SET FirstName=#FirstName,LastName=#LastName,Password=#Password,
EmaildId=#EmaildId,UserId=#UserId WHERE UserId=#UserId1";
var cmd = new SqlCommand(qry,conn7);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId1", Session["username"].ToString());
conn7.Open();
// cmd7.ExecuteNonQuery();
cmd.ExecuteNonQuery();
conn7.Close();
Use Parameters for all you input, don't concatenate strings in queries.
As for your error, you need to specify the connection that the command needs to use:
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;
Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = " UPDATE Registration SET FirstName = #FirstName, LastName = #LastName,"
+ " Password = #Password, EmaildId = #EmaildId WHERE UserId = #UserCondition";
var cmd = new SqlCommand(qry, conn7 );
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserCondition", Session["username"].ToString());
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
'Set' Missing

Inserting values into a SQL Server database using ado.net via C#

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");
}

Categories

Resources