I have inserted values into sql several times but now i am facing problem with the following code
protected void Button1_Click(object sender, EventArgs e)
{
string connstring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
con = new SqlConnection(connstring);
string name = txtName.Text;
string user = txtUser.Text;
string password = txtPwd.Text;
string email = txtEmail.Text;
long phone=Convert.ToInt64(txtPhone.Text);
string address = txtAddr.Text;
string city = txtCity.Text;
string gender = RadioButtonList1.SelectedItem.ToString();
string dob = txtDOB.Text;
string qualification = DropDownList1.SelectedItem.ToString();
string skills = CheckBoxList1.SelectedItem.ToString();
string insertstring = " insert into JobRegisteration values ("+name+","+user+","+password+","+email+","+phone+","+address+","+city+","+gender+","+dob+","+qualification+","+skills+")";
cmd = new SqlCommand(insertstring,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
When I am inserting values into this through asp.net page, its giving following error.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'sbip'.
Invalid column name 'tttt'.
Invalid column name 'ttt'.
The multi-part identifier "tttttt#sss.ss" could not be bound.
Invalid column name 't'.
Invalid column name 'tttt'.
Invalid column name 'Male'.
Invalid column name 'MCA'.
Invalid column name 'C#'.
where tttt, male mca, etc etc are values that are passed from asp page.
thanks!
use parameters like below and also using statements
string connstring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
// change this select statement based on your exact column names
string insertstring = "insert into JobRegisteration ([Name] ,[User] ,[Password] ,[Email] ,[Phone],[Address] ,[City] ,[Gender] ,[Dob] ,[Qualification] ,[Skills]) values (#name ,#user ,#password ,#email ,#phone,#address ,#city ,#gender ,#dob ,#qualification ,#skills)";
using (var con = new SqlConnection(connstring))
using(var cmd = new SqlCommand(insertstring, con))
{
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#user", txtUser.Text);
// give all the parameters..
con.Open();
cmd.ExecuteNonQuery();
}
You need to wrap your inserted values with ' otherwise the database treat them as column names:
string insertstring = " insert into JobRegisteration values ('"+name+"','"+user+"','"+password+"','"+email+"','"+phone+"','"+address+"','"+city+"','"+gender+"','"+dob+"','"+qualification+"','"+skills+"')";
Also, as other suggested you really should rely on Prepared Statements to avoid such problems (among others).
There are many solution to your problem.
1) Try to fit with this format:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
2) as said haim770, surround your values with '
3) use sql parameters way
4) or look at Linq, that's really simplify way to work with database
You need to add single quote ' in your query:
string insertstring = " insert into JobRegisteration values ('"+name+"','"+user+"','"+password+"','"+email+"','"+phone+"','"+address+"','"+city+"','"+gender+"','"+dob+"','"+qualification+"','"+skills+"')";
use using (pun!), bind variables (a.k.a. parameters), format your query, when query seems dubious put what you want explicitly...
protected void Button1_Click(object sender, EventArgs e) {
string name = txtName.Text;
string user = txtUser.Text;
string password = txtPwd.Text;
string email = txtEmail.Text;
long phone = Convert.ToInt64(txtPhone.Text); // <- what about +77(555)123-456-78?
string address = txtAddr.Text;
string city = txtCity.Text;
string gender = RadioButtonList1.SelectedItem.ToString();
string dob = txtDOB.Text;
string qualification = DropDownList1.SelectedItem.ToString();
string skills = CheckBoxList1.SelectedItem.ToString();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString)) {
con.Open();
using(var cmd = con.CreateCommand()) {
cmd.CommandText =
// replace all "field_for_*" for actual fields
#"insert into JobRegisteration(
field_for_name,
field_for_user,
field_for_password,
field_for_email,
field_for_phone,
field_for_address,
field_for_city,
field_for_gender,
field_for_dob,
field_for_qualification,
field_for_skills)
values (
#prm_name,
#prm_user,
#prm_password,
#prm_email,
#prm_phone,
#prm_address,
#prm_city,
#prm_gender,
#prm_dob,
#prm_qualification,
#prm_skills)";
cmd.Parameters.AddWithValue("#prm_name", name);
cmd.Parameters.AddWithValue("#prm_user", user);
cmd.Parameters.AddWithValue("#prm_password", password);
cmd.Parameters.AddWithValue("#prm_email", email);
cmd.Parameters.AddWithValue("#prm_phone", phone);
cmd.Parameters.AddWithValue("#prm_address", address);
cmd.Parameters.AddWithValue("#prm_city", city);
cmd.Parameters.AddWithValue("#prm_gender", gender);
cmd.Parameters.AddWithValue("#prm_dob", dob);
cmd.Parameters.AddWithValue("#prm_qualification", qualification);
cmd.Parameters.AddWithValue("#prm_skills", skills);
cmd.ExecuteNonQuery();
}
}
}
Related
When I run the code the result will be of 'Type' instead of the SUM of Name.
Tried also do the SUM inside the Reader[("Types")] and it displays SUM(Types). It should display the amount of that particular name
Code inside c#:
public void DisplayName()
{
try
{
string Connection = #"Data Source=local;Initial Catalog=Project;Integrated Security=True";
SqlConnection Connect = new SqlConnection(Connection);
string Name;
Console.WriteLine("\nShowing Name\n");
Console.WriteLine("Enter name type: \n");
country = Console.ReadLine();
ConnectingDatabase.Open();
string Query = "SELECT SUM(Types) FROM PersonName WHERE Name = #Name";
SqlCommand Commands = new SqlCommand(Query, ConnectingDatabase, ConnectingDatabase.BeginTransaction());
Commands.Parameters.Add(new SqlParameter("#Name", country));
SqlDataReader Reader = ParaComm.ExecuteReader();
if (Reader.Read())
{
Console.WriteLine("Your name is " + name + " with sum of {0}\n", Reader[("Types")]);
}
Reader.Close();
ParaComm.Transaction.Commit();
Connect.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You should use Group By when use aggregeate function in sql. Try this Sql-Command
string Query = "SELECT SUM(Types) FROM main.Stats Group by column_name WHERE
Name = #Name";
As you learned, you can always reference a column by the column number. i.e 0 in this case.
However, the easiest way to deal with this moving forward, and avoid issues with changes to a query that cause column numbers to change, is to provide an alias for the column.
If you add an alias to your query, changing it to
SELECT SUM(Types) as TypeSum FROM PersonName WHERE Name = #Name you should find that you can access the value using Reader["TypeSum"] syntax.
I hope you can help, I'm trying to update my database file but I keep on getting an error and I'm not sure why, I don't have any problem adding data or displaying data it's just updating the data that I'm having problems with what could be the problem ?
the error is:
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'Full_Name'.
And this is my source code:
public void UpdateTable()
{
try
{
string ID = Txt_IdNumber.Text;//ID Input
string setYearFormat = Tdp_DateOfBirth.Value.ToString("yyyy");//Get only the year to calculate age
string CurrentYear = DateTime.Now.Year.ToString();//Get current year from system settings
int getAge = Convert.ToInt32(CurrentYear) - Convert.ToInt32(setYearFormat);//Calculate Age
string setDOB = Tdp_DateOfBirth.Value.ToString("dd/MM/yyyy");//Set TimeDatePicker to spesific Long date
string Query = "UPDATE UserData" +
"SET Full_Name = #Fullname, Date_Of_Birth = #DateOfBirth, ID_Number = #IdNumber, Age = #Age" +
"WHERE Id = #Id";//Update query
using (SqlConnection Connection = new SqlConnection(ConnectionString))//Connection to ConnectionString
using (SqlCommand Command = new SqlCommand(Query, Connection))//Sql Command to add/Update
{
Connection.Open();//Open Connection
Command.Parameters.AddWithValue("#Id", Dgv_Output.SelectedRows);//Add Values
Command.Parameters.AddWithValue("#Fullname", Txt_Fullname.Text);//Add Values
Command.Parameters.AddWithValue("#DateOfBirth", Convert.ToDateTime(setDOB));//Add Values
Command.Parameters.AddWithValue("#IdNumber", ID);//Add Values
Command.Parameters.AddWithValue("#Age", getAge);//Add Values
Command.ExecuteNonQuery();//Execute Non Query
}
Txt_Fullname.Clear();//Clear Textbox
Txt_IdNumber.Clear();//Clear Textbox
Tdp_DateOfBirth.Value = DateTime.Now;//Set TimeDatePicker to system date
Txt_Fullname.Focus();//Focus on Full Name textbox
}
catch (Exception Err)
{
MessageBox.Show(Err.ToString(), "ERROR");
using (StreamWriter sr = new StreamWriter("UpdateError.txt"))//Write error to file
{
sr.Flush();//Flush existing data
sr.WriteLine(Err);//Write new data
}
}
}
You are missing a whitespace before the set and where clauses:
string Query = "UPDATE UserData " +
// Was missing--^
"SET Full_Name = #Fullname, Date_Of_Birth = #DateOfBirth, ID_Number = #IdNumber, Age = #Age " +
// Here Too--------------------------------------------------------------------------------^
"WHERE Id = #Id";//Update query
You'll have to surround #Full_Name with single quotes:
'#Full_Name'
Using Visual Studio 2017 with SQL Server 2016 Express, and the following method:
protected void subFinish_Click(object sender, EventArgs e)
{
String regPattern = "^\\d{3}-\\d{8}$";
String regPattern2 = "^\\d{11}$";
if (Regex.IsMatch(txtAwbNum.Text, regPattern) || Regex.IsMatch(txtAwbNum.Text, regPattern2))
{
String AwbNum = txtAwbNum.Text;
int doorNum = Convert.ToInt16(ddlDoorNum.SelectedValue);
String driverName = txtDriverName.Text;
String carrier = txtCarrier.Text;
int pieces = Convert.ToInt32(txtPieces.Text);
SqlDecimal GrossWt = SqlDecimal.Parse(txtGrossWt.Text);
SqlDecimal ChargeWt = SqlDecimal.Parse(txtChargeableWt.Text);
String flightNum = ddlFlightNum.ToString();
SqlDateTime date = Convert.ToDateTime(txtDate.Text);
String destination = txtDestination.Text;
String shipper = txtShipper.Text;
Boolean dgCheck = chkDgCheck.Checked;
DateTime today = DateTime.Today;
String dropoffId = DateTime.Today.ToString();
String queryString = "INSERT INTO ExpAwbs (idExpAwbs, Pieces, GrossWt, ChargeWt, Flight, FlightDate, Shipper, Destination, dgCheck) values (#AwbNum, #pieces, #GrossWt, #ChargeWt, #flightNum, #date, #shipper, #destination, #dgCheck);";
String queryString2 = "INSERT INTO Dropoff (idDropoff, DoorNum, Carrier, DriverName, datetime) values (#dropoffID, #doorNum, #carrier, #driverName, #today);";
String connectionString = "Data Source=PCNAME\\SQLEXPRESS;Initial Catalog=TASdb;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(queryString, connection);
SqlCommand command2 = new SqlCommand(queryString2, connection);
command.Parameters.AddWithValue("#AwbNum", AwbNum);
command.Parameters.AddWithValue("#pieces", pieces);
command.Parameters.AddWithValue("#GrossWt", GrossWt);
command.Parameters.AddWithValue("#ChargeWt", ChargeWt);
command.Parameters.AddWithValue("#flightNum", flightNum);
command.Parameters.AddWithValue("#date", date);
command.Parameters.AddWithValue("#destination", destination);
command.Parameters.AddWithValue("#shipper", shipper);
command.Parameters.AddWithValue("#dgCheck", dgCheck);
command2.Parameters.AddWithValue("#doorNum", doorNum);
command2.Parameters.AddWithValue("#carrier", carrier);
command2.Parameters.AddWithValue("#driverName", driverName);
command2.Parameters.AddWithValue("#dropoffId", dropoffId);
command.Connection.Open();
command.ExecuteReader();
command.Connection.Close();
command2.Connection.Open();
command2.ExecuteScalar();
command2.Connection.Close();
}
else
{
MessageBox.Show(this, "Invalid AWB. Please check again and re-submit.");
}
}
When I run this, I get a "String or binary data would be truncated. The statement has been terminated." I don't understand why that could be. I have made sure that all of the fields are less than or equal to the allotted size in the database. The only ones I had question about were the GrossWt and ChargeWt because in the database their datatype is Decimal(6, 1), but I don't think that's the problem because I tried taking them out, and that didn't change anything. Below is the database table designs for the related tables (FlightDate column has actually been updated to be a datetime datatype):
I am receiving the error, Must declare the scalar variable "#ID". Pointing at ExecuteScalar line. I looked on goggle and I think it has something to do with insert parameters for ID. Then again I read there could be a typo error. In my db I have declare column name as ID and Data Type as int, setting 'Is Identity' as Yes. As I am not going to insert ID column manually I think this is why I am having problem(s) and I don't know how to solve this problem.
What I am trying to do is insert username, login date and time. Update on the same column (same id column) when user logs out. Create a new column when user log in again and So on. I am using the similar code that I asked here and here when D Stanley helped me.
Thanks in advance if anyone can help me.
private int ID // forgot to add this.
{ get; set; }
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
string value = cbRoles.Text;
switch (value)
{
case "Manager":
myCon.connectionString();
string dString = string.Empty;
SqlConnection thisConnection = myCon.dbCon;
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
using (var command = myCon.dbCon.CreateCommand())
{
command.CommandText = "SELECT * FROM tblPrivileges";
command.Parameters.AddWithValue("UserName", (txtUserName.Text));
command.Parameters.AddWithValue("Password", (txtPassword.Text));
thisConnection.Open();
var reader = command.ExecuteReader(); //strcomp
{
if (reader.HasRows)
{
while (reader.Read())
{
txtUserName.Text = reader["UserName"].ToString();
txtPassword.Text = reader["Password"].ToString();
MainWindow gobackB = new MainWindow();
gobackB.Show();
LoginSample goback = new LoginSample();
goback.Hide();
}
}
else MessageBox.Show("You have entered incorrect credentials. Please try again", "error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
myCon.dbCon.Close();
nonqueryCommand.CommandType = CommandType.Text;
nonqueryCommand.CommandText = "INSERT tblLoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime)";
//nonqueryCommand.Parameters.AddWithValue("#ID", SqlDbType.Int); this did not work
//nonqueryCommand.Parameters["#ID"].Value = this.ID; this did not work
nonqueryCommand.Parameters.AddWithValue("#UserName", txtUserName.Text);
nonqueryCommand.Parameters.AddWithValue("#LoggedInDate", DateTime.Now);
nonqueryCommand.Parameters.AddWithValue("#LoggedInTime", DateTime.Now.ToString("HH:mm"));
thisConnection.Open();
nonqueryCommand.ExecuteNonQuery(); // error pointing here
nonqueryCommand.CommandText = "SELECT #ID = SCOPE_IDENTITY()";
int id = (int)nonqueryCommand.ExecuteScalar();
// int id = Convert.ToInt32(nonqueryCommand.ExecuteScalar()); this line did not work
this.ID = id;
myCon.dbCon.Close();
break;
The problem is still that you're trying to use the same "scope" with two different SQL commands. Even thought they are the same "variable" in C# in SQL they have different scope.
You'll need to execute both statements in one command and add the #ID parameter as an Output parameter in order to insert and get the identity out:
nonqueryCommand.CommandType = CommandType.Text;
nonqueryCommand.CommandText = "INSERT tblLoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime); " +
"SELECT #ID = SCOPE_IDENTITY()";
nonqueryCommand.Parameters.AddWithValue("#UserName", txtUserName.Text);
nonqueryCommand.Parameters.AddWithValue("#LoggedInDate", DateTime.Now);
nonqueryCommand.Parameters.AddWithValue("#LoggedInTime", DateTime.Now);
nonqueryCommand.Parameters.Add("#ID",SqlDbType.Int).Direction = ParameterDirection.Output;
thisConnection.Open();
nonqueryCommand.ExecuteNonQuery();
int id = (int)nonqueryCommand.Parameters["#ID"];
Here:
nonqueryCommand.CommandText = "SELECT #ID = SCOPE_IDENTITY()";
your SQL assigns a value to a variable that is not declared. Since you are using ExecuteScalar, you probably just mean:
nonqueryCommand.CommandText = "SELECT SCOPE_IDENTITY()";
Note that you might need to cast it - it may come back as decimal.
I'm trying to populate a text box with a forename and surname using the code below:
using (OleDbConnection connName = new OleDbConnection(strCon))
{
String sqlName = "SELECT forename, Surname FROM customer WHERE [customerID]=" + txtCustomerID.Text;
// Create a command to use to call the database.
OleDbCommand commandname = new OleDbCommand(sqlName, connName);
connName.Open();
// Create a reader containing the results
using (OleDbDataReader readerName = commandname.ExecuteReader())
{
readerName.Read(); // Advance to the first row.
txtName.Text = readerName[0].ToString();
}
connName.Close();
}
However I'm getting the error: OleDbException was unhandled.
"no required values for one of more required parameters"
at the ExecuteReader and I'm not sure how to go about fixing this.
EDIT: this code below is nearly the exact same bar for the information in the query but this exception is not coming up for it.
string strCon = Properties.Settings.Default.PID2dbConnectionString;
using (OleDbConnection conn = new OleDbConnection(strCon))
{
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
conn.Open();
// Create a command to use to call the database.
OleDbCommand command = new OleDbCommand(sqlPoints, conn);
// Create a reader containing the results
using (OleDbDataReader reader = command.ExecuteReader())
{
reader.Read(); // Advance to the first row.
txtPoints.Text = reader[0].ToString(); // Read the contents of the first column
}
conn.Close();
}
The usual reason for this is a null or empty string i.e. txtCustomerID.Text has no value so the query being sent to the server is:
SELECT forename, Surname FROM customer WHERE [customerID]=
You can avoid errors like this and SQL Injection, use strongly typed parameters and avoid data truncation using parameterised queries (I have assumed customer ID is an int field)
using (OleDbConnection connName = new OleDbConnection(strCon))
{
String sqlName = "SELECT forename, Surname FROM customer WHERE customerID = #CustomerID";
// Create a command to use to call the database.
using (OleDbCommand commandname = new OleDbCommand(sqlName, connName))
{
//Check the input is valid
int customerID = 0;
if (!int.TryParse(txtCustomerID.Text, out customerID))
{
txtName.Text = "Customer ID Text box is not an integer";
return;
}
connName.Open();
// Add the parameter to the command
commandname.Parameters.Add("#CustomerID", OleDbType.Integer).Value = customerID;
// Create a reader containing the results
using (OleDbDataReader readerName = commandname.ExecuteReader())
{
readerName.Read(); // Advance to the first row.
txtName.Text = readerName[0].ToString();
}
connName.Close();
}
}
You have to encode parameters used in string queries.
String sqlName = String.Format("SELECT forname, Surname FROM customer WHERE customerID={0}",txtCustomerID.Text);
But I advice you against using SQL queries hard-coded in strings. Its easy way for SQL Injection attack. You should use parammeters instead.