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'
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'm relatively new but I've been researching this issue for over 2 days, so I think I've done my due diligence ... however if this has already been answered before I apologize.
My basic issue is I'm trying to create some dependent combo boxes. The wrinkle is the displayed value is typically not the lookup value for the next query/Combo box (I'm using an OLEDB compliant data base)
For example: Table1 (T1) contains ID (int) & NM (string), Table2 (T2) contains ID (int) & STATUS (string). I run Query1 (Q1) to display T1.NM in Combobox1 (CB1), when selected I run Query1a to lookup/get the selected Table1.ID to pass to Query2 that populates Combobox2. The connection string and Q1 work fine, CB1 displays properly, but once I select this error is thrown:
"OleDbException .. SQL Passthru expression ... using equals (=) has components that are of different data types"
// ** Initial connection & populate CB1 - This works fine **
public void comboboxLoad()
{
string conn3str = <Connection String >;
string query1 = "select NM from Table1 where REFVALUE=1 ; ";
OleDbConnection conn3 = new OleDbConnection(conn3str);
OleDbCommand tblRow1 = new OleDbCommand(query1, conn3);
OleDbDataReader rdRow1;
try
{
conn3.Open();
lblConnState.Text = "Connection Successful";
rdRow1 = tblRow1.ExecuteReader();
while (rdRow1.Read())
{
int colindx1 = rdRow1.GetOrdinal("NM");
string sItbl = rdRow1.GetString(colindx1);
CB1.Items.Add(sItbl);
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
// ** Get value from CB1, create query to populate CB2 **
private void CB1_SelectedIndexChanged(object sender, EventArgs e)
{
string conn3str = <Connection String >;
OleDbConnection conn3 = new OleDbConnection(conn3str);
conn3.Open();
// Pass the selected value from CB1 (string) equal to Table1.NM (string)
string query1a = "select ID from Table1 where NM = '" + CB1.Text + "' ; ";
OleDbCommand TabID = new OleDbCommand(query1a, conn3);
int TabId2 = Convert.ToInt32(TabID.ExecuteScalar());
// Pass the variable TabId2 (int) equal to Table2.ID (int)
string query2 = "select STATUS from Table2 where ID = '" + TabId2 + "'; ";
OleDbCommand tblRow2 = new OleDbCommand(query2, conn3);
// OleDbDataReader rdTabID;
// OleDbDataReader rdRow2;
try
{
OleDbDataReader rdRow2 = TabID.ExecuteReader();
OleDbDataReader rdTabID = tblRow2.ExecuteReader(); // ** Error points to this line **
while (rdRow2.Read())
{
int TabIdidx = rdTabID.GetOrdinal("ID");
string TabIDVal = rdTabID.GetString(TabIdidx);
// Pass reference ID to label on form
lblBTableID.Text = TabId2.ToString();
int colindx1 = rdRow2.GetOrdinal("STATUS");
string sIntVal = rdRow2.GetString(colindx1);
cmbLowLvl.Items.Add(sIntVal);
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
Are you positive you're getting a value back on this line int TabId2 = Convert.ToInt32(TabID.ExecuteScalar());?
Convert.ToInt32 doesn't throw a ArgumentNullException like int.Parse does so it's possible that the variable is not getting set.
Also you may want to consider changing your queries to use parameterized SQL rather than concatenation for security purposes.
https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
I've been able to figure out the problem. I'm really not sure why it didn't work originally, but I think it was a reader mismatch, since I was only looking for a single value back from the query ExecuteScalar() seemed to do the trick and I didn't need the 'while' loop. The working code is below.
Next I'll need to pass this return value (ID) in my next query to populate CB2. Thanks #
private void CB1_SelectedIndexChanged(object sender, EventArgs e)
{
string conn3str = <Connection String >;
OleDbConnection conn3 = new OleDbConnection(conn3str);
// Pass the selected value from CB1 (string) equal to Table1.NM (string) but return the int ID.
OleDbCommand tblRow2 = new OleDbCommand("select ID from Table1 where NM= '"+ CB1.Text +"' ;" , conn3);
try
{
conn3.Open();
string r2 = Convert.ToString(tblRow2.ExecuteScalar());
MessageBox.Show(r2);
lblBTableID.Text = "ID Code= " + r2;
conn3.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
I'm getting a SqlException in my code:
Incorrect syntax near 'MatricNO'
Here is the code:
public static StudentDetail GetStudent(string MatricNO)
{
//Calling on the connection class and get connection method
SqlConnection connection = ConnectionClass.GetConnection();
//Sql select statement that reads from the database
string selectStatement = "SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName" +
"FROM StudentInfo" +
"WHERE MatricNO=#MatricNO";
SqlCommand selectCommand=new SqlCommand(selectStatement,connection);
selectCommand.Parameters.AddWithValue("#MatricNO", MatricNO);
try
{
connection.Open();
SqlDataReader reader = selectCommand.ExecuteReader(CommandBehavior.SingleRow);
if(reader.Read())
{
//Read the database information into the StudentDetail Class
StudentDetail studentDetail=new StudentDetail();
studentDetail.Studentmatricno = reader["MatricNO"].ToString();
studentDetail.Faculty = reader["Faculty"].ToString();
studentDetail.Dept = reader["Department"].ToString();
studentDetail.Course = reader["Course"].ToString();
studentDetail.Firstname = reader["FirstName"].ToString();
studentDetail.Middlename = reader["MiddleName"].ToString();
studentDetail.Surname = reader["LastName"].ToString();
return studentDetail; //return all that has been read to the student detail class
}
else
{
// return null if queried record does not exist
return null;
}
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
Can anyone help me resolve this issue?
You need spaces between FROM and SELECT, and FROM and WHERE clause
string selectStatement = "SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName" +
" FROM StudentInfo" +
" WHERE MatricNO=#MatricNO";
Its always better to look at the generated SQL from string concatenation and trying it directly on DB.
Your SQL query needs spaces after the field list and table name:
string selectStatement =
"SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName " +
"FROM StudentInfo " +
"WHERE MatricNO=#MatricNO";
You could also use a verbatim string literal:
string selectStatement =
#"SELECT MatricNO,Faculty,Department,Course,FirstName,MiddleName,LastName
FROM StudentInfo
WHERE MatricNO=#MatricNO";
My table structure is as follows:
Session
--------------
SessionID (PK)
RoomID
SessionDate
SessionTimeStart
SessionTimeEnd
I have a following query which will always return one row and display in DGV. I use DataAdapter for connection:
DataTable queryResult = new DataTable();
string ConnStr = "Data Source=DUZY;Initial Catalog=AutoRegSQL;Integrated Security=True";
SqlConnection MyConn = new SqlConnection(ConnStr);
MyConn.Open();
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
SqlCommand command = new SqlCommand(query, MyConn);
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(queryResult);
I would like to save the query result into multiple strings representing table columns, i.e.
SessionIDstring = query result for SessionID column
RoomIDstring = query result for RoomID column
and so on...
Is it possible to achieve it using one query, or do I have to create 5 queries for each column?
Something similar to this, perhaps, using ADO.NET?
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
using (var connection = new SqlConnection(ConnStr))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
// Note that reader[x] has the equivalent type to the type
// of the returned column, converted using
// http://msdn.microsoft.com/en-us/library/cc716729.aspx
// .ToString() if the item isn't null is always ok
string SessionIDstring = reader[0].ToString(); // it should be an int
// reading it twice is ok
int RoomID = (int)reader[1]; // it should be an int
string RoomIDstring = reader[1].ToString(); // it should be an int
if (reader.Read())
{
throw new Exception("Too many rows");
}
}
else
{
throw new Exception("No rows");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This code was adapted from MSDN ADO.NET Code Examples. I added some usings and made it single row. I don't even want to know why MSDN examples don't go the full length with using.
Note that SqlDataAdapter are built to recover multiple rows/big data and put them in a DataSet. You can use them for single row data, but it's much easier to simply use a SqlDataReader if you only want to fill some variables.
declare #col1 int
declare #col2 varchar(42)
select #col1 = col1
, #col2 = col2
, ....
You could create a class like so...
public class SessionDto
{
public string SessionID {get; set;}
public string RoomID {get; set;}
public string SessionDate {get; set;}
public string SessionTimeStart {get; set;}
public string SessionTimeEnd {get; set;}
}
And then have a method that takes a Room ID and builds your session object
public SessionDto GetSessionData(int roomId)
{
using (var cnn = new SqlConnection(ConnStr))
{
SessionDto sessionDto;
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
cnn.Open();
using (var cmd = new SqlCommand(query,cnn))
{
cmd.Parameters.Add("#RoomID", SqlDbType.Char).Value = roomId;
using (var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
sessionDto = new sessionDto{
SessionID = rdr.GetString(0),
RoomID = rdr.GetString(1),
SessionDate = rdr.GetString(2),
SessionTimeStart = rdr.GetString(3),
SessionTimeEnd = rdr.GetString(4)
};
}
}
}
}
}
return sessionDto;
}
A lot of this is hand typed as I havent got access to VS right now,
but you should get it to work.
Also, I have used rdr.GetString(), there are other methods for GetType().
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();
}
}
}