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
Related
I am unable to send lasted inserted autoincrement id value to another table
this is my code
i am getting error is Must declare the scalar variable "#userid".
int ID;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()", cn);
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
cmd.ExecuteNonQuery();
ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
SqlCommand cmd2 = new SqlCommand("insert into sampfk values(#emailid,#address,#userid)", cn);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text);
cmd2.Parameters.AddWithValue("#userid", ID);
cn.Open();
cmd2.ExecuteNonQuery();
cn.Close();
cmd.Dispose();
TextBox3.Text = "";
TextBox4.Text = "";
I think I got your problem.you have written
SqlCommand cmd2 = new SqlCommand("insert into sampfk values (#userid, #address, #emailid)", cn);
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text)
but executing
cmd2.ExecuteNonQuery();
you should add parameter in cmd2 not cmd like as
cmd2.Parameters.AddWithValue("#userid", ID);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text)
You can do above in single step, you should use using more and try to nest query if possible. Opening TCP connection frequently has some acknowledgement overheads.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString))
{
string query = #"INSERT INTO sampdb VALUES (#name,#phone);
INSERT INTO sampfk VALUES (SCOPE_IDENITTY(), #address, #emailid); ";
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Check the following line.
ID = Convert.ToInt32(cmd.ExecuteScalar());
If this doesn't return anything, then use a default value for ID, maybe 0.
Or add a default value in the declaration as int id = 0;
try this
using (SqlConnection cn = new SqlConnection(connectionStr))
{
string sql1 = "insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()";
using (SqlCommand cmd = new SqlCommand(sql1, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
ID = cmd.ExecuteNonQuery();
}
//ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
string sql2 = "insert into sampfk values (#userid, #address, #emailid)";
using (SqlCommand cmd = new SqlCommand(sql2, cn))
{
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
con.Dispose();
con.Close();
}
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));
i am getting this error so often, i can't find out what's wrong in here?
con.Open();
String query = "INSERT INTO user (username,[password]) values(a,b)";
OleDbCommand cmd1 = new OleDbCommand(query, con);
cmd1.Parameters.AddWithValue("a",textBox1.Text);
cmd1.Parameters.AddWithValue("b", textBox2.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
SqlParameters should start with # like #Name. try this:
con.Open();
String query = "INSERT INTO user (Username, [Password]) values(#Username, #Password)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#Username",textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
Read Using Variables and Parameters
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;
I make a program that saves and update a data from the database, I can save and read data, I can also update but the problem is, I can't select the "ID" as the index, here is my sample code using "ID" as the index,
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE [ID] = #id";
cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();
}
and here is my update code that works, but the index is the "firstname",
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE FirstName = #firstname";
//cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();`
}
It works but the problem is I can't update the "FirstName", Is there a way that I can also update the Firstname? or use the "ID" as the index? thanks
I don't know what database you are going against, however, I don't know if the OleDB is being picky on the ordinal sequence of your parameters. ie: Have you tried putting your "ID" parameter in the last position to match the actual order of the fields of your update command? I don't know if it's throwing it out.
You should add the following code after the last line of ID:
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE [ID] = #id";
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery(); {
MessageBox.Show("Update Success!");
cn.Close();
}