How to insert new value autonumber by parameters to access - sql

When I press insert, I receive the error: Syntax error in INSERT INTO statement
EmployeeID (Autonumber)
EmployeeName(Text)
Position(Text)
Address(Text)
OleDbDataAdapter ad;
DataSet ds;
DataTable dt;
protected void SetInsertParameters()
{
string sql = "INSERT INTO Employee(EmployeeName,Position,Address)"+
" VALUES (#EmployeeName,#Position,#Address)";
ad.InsertCommand = new OleDbCommand(sql, con);
OleDbParameter param = new OleDbParameter("#EmployeeName", OleDbType.VarChar);
param.SourceColumn = "EmployeeName";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
param = new OleDbParameter("#Position", OleDbType.VarChar);
param.SourceColumn = "Position";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
param = new OleDbParameter("#Address", OleDbType.VarChar);
param.SourceColumn = "Address";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
}
void InsertNewValues()
{
dt = ds.Tables["Employee"];
DataRow row = dt.NewRow();
row[0] = txt_employeeID.Text;
row[1] = txt_name.Text;
row[2] = txt_position.Text;
row[3] = txt_address.Text;
dt.Rows.Add(row);
ad.Update(ds, "Employee");
ad.Fill(ds);
}

Position is a reserved word and must be bracketed:
"INSERT INTO Employee(EmployeeName,[Position],Address)"

Related

How to iterate through the table and get the value of a cell? (MVC)

I have this table called "Events" with where there are columns named 'EquipID' and 'EmailSent' respectively.
The default value for 'EmailSent' is "no" when a data is inserted. Now I have to run a query to iterate through every single row whether an e-mail has been sent or not based on the value. If the query reads 'no', then I have to perform a SMTP function to send a mail according to the corresponding 'EquipID' to it, where I have to fetch the cell value of it. A row can be skipped if the query reads 'yes' instead.
Now I have no idea on how to call a table and query the iteration to get the value of the cells only if the value of 'EmailSent' is 'no'.
I have attached the table design and data together.
I did something like this so far.
con.Open();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MVCConnectionString"].ConnectionString))
{
//replace this with your query
using (var command = new SqlCommand("SELECT EventID, EquipID, EmailSent FROM Events", con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
if (reader["EmailSent"].ToString() == "no")
{
string IDIDID = reader["EquipID"].ToString();
//add your function to send email
string sqlView = "SELECT * FROM [NewEquipment] INNER JOIN [User] ON [NewEquipment].[UserID] = [User].[UserID] WHERE EquipID = '" + IDIDID + "'";
using (SqlCommand yes = new SqlCommand(sqlView, con))
{
SqlDataReader read = yes.ExecuteReader();
if (read.Read())
{
string UserEmail = read["UserEmailAdd"].ToString();
string UserFullName = read["UserFullName"].ToString();
string EquipIDID = read["EquipID"].ToString();
string ModelNo = read["ModelNo"].ToString();
string ModelDesc = read["ModelDesc"].ToString();
string CalType = read["CalType"].ToString();
string CalDate = read["EquipCalDueDate"].ToString();
DateTime caldate = DateTime.Parse(CalDate);
string DateDate = caldate.ToString("MM-dd-yyyy");
MailMessage mail = new MailMessage();
mail.To.Add(UserEmail);
mail.From = new MailAddress("keysight#keysight.com");
mail.Subject = "Reminder on Equipment's Cal Due Date";
mail.IsBodyHtml = true;
string Body = "Greetings " + UserFullName + "<br/><br/>This email is to remind you that you have " + "<b>10 days </b>" + "left before you can send the equipment for calibration. Below are the details of the respective equipment: " +
"<br/><br/>Equipment ID: " + EquipIDID + "<br/>Model No.: " + ModelNo + "<br/>Model Description: " + ModelDesc + "<br/>Cal Type: " + CalType + "<br/>Equipment Status: " + "<b>CRITICAL</b>" +
"<br/>Equipment Cal Due Date: " + DateDate + "<br/><br/>Thank you." + "<br/><br/>Regards," + "<br/>Keysight Technologies";
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.cos.is.keysight.com";
smtp.Port = 25;
smtp.Send(mail);
}
read.Close();
con.Close();
}
}
}
}
}
}
}
con.Close();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MVCConnectionString"].ConnectionString))
{
//replace this with your query
using (var command = new SqlCommand("SELECT eventid,eqipid,emailsent FROM TableName", connection))
{
connection.Open();
using (var reader = command.ExecuteReader()){
if(reader.HasRows){
while(reader.Read()){
if (reader["emailsent"].ToString()=="NO"){
//add your function to send email
}
}
}
}
}
Thank you guys for your help. I found the answer for it. I've attached it below.
using (var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"))
{
using (var command = con.CreateCommand())
{
command.CommandText = "SELECT EventID, EquipID, EmailSent, EquipCalDueDate, ThemeColor FROM Events";
con.Open();
using (var reader = command.ExecuteReader())
{
var indexOfColumn1 = reader.GetOrdinal("EventID");
var indexOfColumn2 = reader.GetOrdinal("EquipID");
var indexOfColumn3 = reader.GetOrdinal("EmailSent");
var indexOfColumn4 = reader.GetOrdinal("EquipCalDueDate");
var indexOfColumn5 = reader.GetOrdinal("ThemeColor");
while (reader.Read())
{
var value1 = reader.GetValue(indexOfColumn1);
var value2 = reader.GetValue(indexOfColumn2);
var value3 = reader.GetValue(indexOfColumn3);
var value4 = reader.GetValue(indexOfColumn4);
var value5 = reader.GetValue(indexOfColumn5);
if (value5.ToString() == "red" && value3.ToString() == "no") {
string sqlView = "SELECT * FROM [NewEquipment] INNER JOIN [User] ON [NewEquipment].[UserID] = [User].[UserID] WHERE EquipID = '" + value2.ToString() + "'";
using (SqlCommand yes = new SqlCommand(sqlView, con))
{
SqlDataReader read = yes.ExecuteReader();
if (read.Read())
{
string UserEmail = read["UserEmailAdd"].ToString();
string UserFullName = read["UserFullName"].ToString(); string EquipIDID = read["EquipID"].ToString();
string ModelNo = read["ModelNo"].ToString();
string ModelDesc = read["ModelDesc"].ToString();
string CalType = read["CalType"].ToString(); string CalDate = read["EquipCalDueDate"].ToString();
DateTime Edate = DateTime.Parse(CalDate);
double remainingDays = (Edate - DateTime.Now).TotalDays;
int rDays = (int)Math.Round(remainingDays, MidpointRounding.AwayFromZero);
MailMessage mail = new MailMessage();
mail.To.Add(UserEmail);
mail.From = new MailAddress("keysight#keysight.com");
mail.Subject = "Reminder on Equipment's Cal Due Date";
mail.IsBodyHtml = true;
string Body = "Greetings " + UserFullName + "<br/><br/>This email is to remind you that you have " + "<b>"+ rDays + " days </b>" + "left before you can send the equipment for calibration. Below are the details of the respective equipment: " +
"<br/><br/>Equipment ID: " + EquipIDID + "<br/>Model No.: " + ModelNo + "<br/>Model Description: " + ModelDesc + "<br/>Cal Type: " + CalType + "<br/>Equipment Status: " + "<b>CRITICAL</b>" +
"<br/>Equipment Cal Due Date: " + CalDate + "<br/><br/>Thank you." + "<br/><br/>Regards," + "<br/>Keysight Technologies";
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.cos.is.keysight.com";
smtp.Port = 25;
smtp.Send(mail);
}
read.Close();
string yyy = "SELECT * FROM [Events] WHERE EquipID='" + value2.ToString() + "'";
using (SqlCommand cmdcmd = new SqlCommand(yyy, con))
{
SqlDataReader readread = cmdcmd.ExecuteReader();
if (readread.Read())
{
string sql = "UPDATE Events SET EmailSent='yes' WHERE EquipID = '" + value2.ToString() + "'";
SqlCommand cmd1 = new SqlCommand(sql, con);
cmd1.ExecuteNonQuery();
}
readread.Close();
}
}
}
}
}
con.Close();
}
}

ORA-00933: oracle 8i

I want to use join in Oracle 8i. I have my query as below.
I have this query of getting data from two tables using an join, but I get the error SQL command not properly ended.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID," +
" DLOG.RELEASEID AS RELEASE_BUILD," +
" TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE," +
" DLOGDET.DEPLOYREQUEST AS BAAR_RFD," +
" DLOG.FILENAMEEXT_VC AS SCRIPT_NAME," +
" DLOG.VERSION," +
" DLOG.REQUEST," +
" DLOG.NOTE AS COMMENTS" +
" FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET" +
" JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO;";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
My target is to insert records into a table.
Keep everything in one set of " and also you only need a single ; to end the SQL query outside of the double quotes.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID,
DLOG.RELEASEID AS RELEASE_BUILD,
TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE,
DLOGDET.DEPLOYREQUEST AS BAAR_RFD,
DLOG.FILENAMEEXT_VC AS SCRIPT_NAME,
DLOG.VERSION,
DLOG.REQUEST,
DLOG.NOTE AS COMMENTS
FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET
JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
Oracle 8i did not support standard ANSI SQL JOIN syntax.
That feature was introduced in Oracle 9i Release 2 (aka Oracle 9.2)
Quote from the chapter "What's New in SQL Reference"
SELECT [...] has new ANSI-compliant join syntax.
Don't combine the, strings put all in one.

SQL Dynamic Query - Incorrect syntax near '#WhereClause'

//_whereclause is: where (lastName like '%Davis%')
public static MyList GetAll(string _whereclause)
{
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
string selectSQL = "";
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable]";
if (_whereclause != string.Empty)
{
selectSQL += " #WhereClause";
}
using (SqlCommand myCommand = new SqlCommand(selectSQL, myConnection))
{
myCommand.CommandType = CommandType.Text;
SqlParameter whereClauseParam = new SqlParameter("#WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause;
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{..............
If I run it with the #WhereClause I get error:
Incorrect syntax near '#WhereClause'.
Your select query should be like
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable] where (lastName like '%" + #WhereClause + "%')";
Assuming that:
SqlParameter whereClauseParam = new SqlParameter("#WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause; //Here you are getting the value as 'Davis'
But in case you are getting the value in it as where (lastName like '%Davis%') then you simply need to add a space after
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable] ";
^^ here

"Procedure or function 'UPDATE' expects parameter '#Id', which was not supplied" in Windows Form

We created a Windows Form to update a table in SQL Server.
First I click Enter ID to retrieve details from database, then after changing some data, when I click on Update button, I get an error:
Procedure or function 'UPDATE' expects parameter '#Id', which was not supplied.
Windows Form Design :
Click here
Error :
Click here
Code for Windows Form:
public partial class Update : Form
{
string connectionString = #"Data Source=AMAR;Initial Catalog=Hotel;Integrated Security=True";
public Update()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
TestObject t = null;
string spName = "Get";
//string queryText = "Select * from TestTable where Id = " +txtId.Text;
SqlConnection conn = new SqlConnection(connectionString);
//SqlCommand com = new SqlCommand(spName, conn);
SqlCommand com = new SqlCommand(spName, conn);
com.Parameters.AddWithValue("#Id", ID.Text);
com.CommandType = CommandType.StoredProcedure;
conn.Open();
using (SqlDataReader reader = com.ExecuteReader())
{
t = new TestObject();
while (reader.Read())
{
t.Id = reader["ID"].ToString();
t.Status = reader["Status"].ToString();
t.FName = reader["FirstName"].ToString();
t.LName = reader["LastName"].ToString();
t.Addr = reader["Address"].ToString();
t.City = reader["City"].ToString();
t.State = reader["State"].ToString();
t.Country = reader["Country"].ToString();
t.PhoneNo = reader["PhoneNo"].ToString();
t.Email = reader["EmailId"].ToString();
t.Pin = reader["Pincode"].ToString();
t.CheckIn = reader["CheckIn"].ToString();
t.CheckOut = reader["CheckOut"].ToString();
t.AdultNo = reader["AdultNo"].ToString();
t.ChildNo = reader["InfantNo"].ToString();
t.InfantNo = reader["InfantNo"].ToString();
t.RoomNo = reader["RoomNo"].ToString();
};
}
Statustxt.Text = t.Status;
txtfName.Text = t.FName;
txtlName.Text = t.LName;
txtAddr.Text = t.Addr;
City.Text = t.City;
State.Text = t.State;
Country.Text = t.Country;
PhoneNo.Text = t.PhoneNo;
EmailID.Text = t.Email;
Pincode.Text = t.Pin;
CheckIN.Text = t.CheckIn;
CheckOut.Text = t.CheckOut;
Adult.Text = t.AdultNo;
Child.Text = t.ChildNo;
Infant.Text = t.InfantNo;
RoomNo.Text = t.RoomNo;
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
string Stat = Statustxt.Text;
string FirstName = txtfName.Text;
string LastName = txtlName.Text;
string Address=txtAddr.Text;
string Cities=City.Text;
string States= State.Text;
string Countries =Country.Text;
string PhoneNos= PhoneNo.Text;;
string EmailId= EmailID.Text;
string PinCode=Pincode.Text;
string CIn=CheckIN.Text;
string COut=CheckOut.Text;
string AdultNo=Adult.Text;
string ChildNo=Child.Text;
string InfantNo=Infant.Text;
string RoomNos=RoomNo.Text;
TestObject obj = new TestObject();
obj.Stat=Statustxt.Text;
obj.FirstName = txtfName.Text;
obj.LastName = txtlName.Text;
obj.Address=txtAddr.Text;
obj.Cities=City.Text;
obj.States= State.Text;
obj.Countries =Country.Text;
obj.PhoneNos= PhoneNo.Text;;
obj.EmailId= EmailID.Text;
obj.PinCode=Pincode.Text;
obj.CIn=CheckIN.Text;
obj.COut=CheckOut.Text;
obj.AdultNo=Adult.Text;
obj.ChildNo=Child.Text;
obj.InfantNo=Infant.Text;
obj.RoomNos=RoomNo.Text;
string spName = "UPDATE";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(spName, conn);
conn.Open();
com.Parameters.AddWithValue("#Stat", obj.Stat);
com.Parameters.AddWithValue("#FirstName", obj.FirstName);
com.Parameters.AddWithValue("#LastName", obj.LastName);
com.Parameters.AddWithValue("#Address", obj.Address);
com.Parameters.AddWithValue("#Cities", obj.Cities);
com.Parameters.AddWithValue("#States", obj.States);
com.Parameters.AddWithValue("#Countries", obj.Countries);
com.Parameters.AddWithValue("#PhoneNos", obj.PhoneNos);
com.Parameters.AddWithValue("#EmailId", obj.EmailId);
com.Parameters.AddWithValue("#PinCode", obj.PinCode);
com.Parameters.AddWithValue("#CIn", obj.CIn);
com.Parameters.AddWithValue("#COut", obj.COut);
com.Parameters.AddWithValue("#AdultNo", obj.AdultNo);
com.Parameters.AddWithValue("#ChildNo", obj.ChildNo);
com.Parameters.AddWithValue("#InfantNo", obj.InfantNo);
com.Parameters.AddWithValue("#RoomNos", obj.RoomNos);
com.CommandType = CommandType.StoredProcedure;
com.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Customer Details updated in system");
}
}
SQL Server stored procedure:
ALTER PROCEDURE [dbo].[UPDATE]
#Id int,
#Stat nvarchar(100),
#FirstName nvarchar(100),
#LastName nvarchar(100),
#Address nvarchar(100),
#Cities nvarchar(100),
#States nvarchar(100),
#Countries nvarchar(100),
#PhoneNos int,
#EmailId nvarchar(100),
#PinCode int,
#CIn nvarchar(100),
#COut nvarchar(100),
#AdultNo int,
#ChildNo int,
#InfantNo int,
#RoomNos int
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
UPDATE [Hotel].[dbo].[Details] SET
[Status] = #Stat,
[FirstName] = #FirstName,
[LastName] = #LastName,
[Address] = #Address,
[City] = #Cities,
[State] =#States ,
[Country] = #Countries,
[PhoneNo] = #PhoneNos,
[EmailId] = #EmailId,
[Pincode] = #PinCode,
[CheckIn] = #CIn,
[CheckOut] = #COut,
[AdultNo] = #AdultNo,
[ChildNo] = #ChildNo,
[InfantNo] = #InfantNo,
[RoomNo] = #RoomNos
WHERE ID = #Id
END
a. as Mitch Wheat wrote in the comments, NEVER use keywords as procedures names.
b. as marc_s wrote in his comment - stop using .AddWithValue(). read the article he links to.
c. you never provide the #id parameter to the command , this is why you get the error.
d. this has nothing to do with winforms.
e. in the future, Please provide only the relevant code. if the problem is in the update button click, we don't need to see the entire form class, only the button click event handler.

sql statement supposed to have 2 distinct rows, but only 1 is returned

I have an sql statement that is supposed to return 2 rows. the first with psychological_id = 1, and the second, psychological_id = 2. here is the sql statement
select * from psychological where patient_id = 12 and symptom = 'delire';
But with this code, with which I populate an array list with what is supposed to be 2 different rows, two rows exist, but with the same values: the second row.
OneSymptomClass oneSymp = new OneSymptomClass();
ArrayList oneSympAll = new ArrayList();
string connStrArrayList = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\PatientMonitoringDatabase.mdf; " +
"Initial Catalog=PatientMonitoringDatabase; " +
"Integrated Security=True";
string queryStrArrayList = "select * from psychological where patient_id = " + patientID.patient_id + " and symptom = '" + SymptomComboBoxes[tag].SelectedItem + "';";
using (var conn = new SqlConnection(connStrArrayList))
using (var cmd = new SqlCommand(queryStrArrayList, conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
oneSymp.psychological_id = Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy = (DateTime)rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date = (DateTime)rdr["psy_start_date"];
oneSymp.psy_end_date = (DateTime)rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}
}
conn.Close();
}
OneSymptomClass testSymp = oneSympAll[0] as OneSymptomClass;
MessageBox.Show(testSymp.psychological_id.ToString());
the message box outputs "2", while it's supposed to output "1". anyone got an idea what's going on?
You're adding the same instance to the ArrayList twice. Try this:
List<OneSymptomClass> oneSympAll = new List<OneSymptomClass>();
string connStrArrayList =
"Data Source=.\\SQLEXPRESS;" +
"AttachDbFilename=|DataDirectory|\\PatientMonitoringDatabase.mdf; " +
"Initial Catalog=PatientMonitoringDatabase; " +
"Integrated Security=True";
Patient patientID;
string queryStrArrayList =
"select * from psychological where patient_id = " +
patientID.patient_id + " and symptom = '" +
SymptomComboBoxes[tag].SelectedItem + "';";
using (var conn = new SqlConnection(connStrArrayList))
{
using (var cmd = new SqlCommand(queryStrArrayList, conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
OneSymptomClass oneSymp = new OneSymptomClass();
oneSymp.psychological_id =
Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy =
(DateTime) rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date =
(DateTime) rdr["psy_start_date"];
oneSymp.psy_end_date =
(DateTime) rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}
}
conn.Close();
}
}
MessageBox.Show(oneSympAll[0].psychological_id.ToString());
MessageBox.Show(oneSympAll[1].psychological_id.ToString());
Note that I replaced the ArrayList with a List<OneSymptomClass>. There is no reason to use ArrayList unless you're using .NET 1.1.
thx for the tip John Saunders. I added a line that makes it work. was that what you were gonna suggest me?
while (rdr.Read())
{
oneSymp = new OneSymptomClass();
oneSymp.psychological_id = Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy = (DateTime)rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date = (DateTime)rdr["psy_start_date"];
oneSymp.psy_end_date = (DateTime)rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}