This code returns the following error:
"System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'a51'"
a51 is the correct value inside of the record I'm looking for in the EstablishmentCode column of the Establishments table. Account ID is used to find all entries on the Establishments table with that account ID and populate a dataset with Establishment Code values. Account ID value comes from a session variable. Then I use each of these values in a loop where each iteration calls a datareader while loop. Hope I explained this clearly, but I would gladly clarify more if needed. Here's my code.
myConnection.Open();
SqlCommand getEst = new SqlCommand("SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, myConnection);
da = new SqlDataAdapter(getEst);
ds = new DataSet();
da.Fill(ds);
int maxrows = ds.Tables[0].Rows.Count;
for (int x = 0; x < maxrows; x++)
{
getPhones = new SqlCommand("SELECT * FROM DispatcherPhones WHERE EstablishmentCode = " + ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString(), myConnection);
myReader = getPhones.ExecuteReader();
while (myReader.Read())
{
Response.Write("<section id='phone" + myReader["Phone"].ToString() + "' style='padding:20px'>");
Response.Write("<section>Phone Number<br><div class='phone'>" + myReader["Phone"].ToString() + "</div></section>");
Response.Write("<section>Location Code<br><div class='name'>" + myReader["EstablishmentCode"].ToString() + "</div></section>");
Response.Write("<section>Active<br><div class='name'>" + myReader["Active"].ToString() + "</div></section>");
Response.Write("<section class='flex phoneButtonSection'>");
Response.Write("<button type=\"button\" onclick=\"showPhoneForm('" + myReader["ID"].ToString() + "');\">CHANGE</button>");
Response.Write("<button type=\"button\" onclick=\"deletePhones('" + myReader["ID"].ToString() + "');\">DELETE</button>");
Response.Write("</section>");
Response.Write("</section>");
}
myReader.Close();
}
myReader.Close();
myConnection.Close();
String literals in SQL are denoted by single quotes ('s) which are missing for your value:
getPhones = new SqlCommand
("SELECT * " +
"FROM DispatcherPhones
"WHERE EstablishmentCode = '" +
// Here -------------------^
ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString() +
"'" // And here
, myConnection);
Mandatory comment: concatinating strings in order to create SQL statements may leave your code exposed to SQL injection attacks. You should consider using prepared statements instead.
Related
I've got a question about SQL language which I couldn't find an answer for. I want SQL to automatically insert a number based off how much rows there are. Using an ASP.NET website I'm adding new rows and deleting rows. This means when I delete rows I want the table to automatically respond to that.
It is pretty hard to explain for me, so I already did some thinking ofcourse. I can fill it in using a C# code but when a row is deleted it ofcourse does not automatically change.
if (kisten < 4)
{
staple = 1;
}
else
{
if (staple1 >= 4)
{
staple = stapel2 + 1;
}
else
{
stapel = stapel2;
}
}
So what this means is that one staple contains 4 blocks. But I want if one row gets removed from the staple the first row of the second staple gets added to the first staple, so it gets value '1'.
Hope I am clear enough. If not, please don't hesitate to ask.
EDIT:
I am using SQL Server indeed. Here is a clear example of what I mean:
This is when everything is inserted using C# and as u can see it works fine.
This is when rows get deleted. As you can see the column 'Stapel' does not automatically change the number
What I want when rows get deleted
So after hours of trying I found a solution which works perfectly. Like so:
SqlCommand cmd11 = new SqlCommand("select count(kistid) from [dbo].[kist] where rij = '" + rij + "'", con);
int countrij = (Int32)cmd11.ExecuteScalar();
int procent = (4 / countrij * 100);
int hoeveel;
int hoeveel2 = (countrij % 4);
int hoeveel1;
if (hoeveel2 == 0)
{
hoeveel = (countrij / 4);
hoeveel1 = hoeveel;
for (int i = 0; i < hoeveel; i++)
{
SqlCommand sqlquery5 = new SqlCommand("UPDATE TOP (" + countrij + ") Kist SET Stapel ='" + hoeveel1 + "' WHERE Rij ='" + rij + "'");
sqlquery5.CommandType = System.Data.CommandType.Text;
sqlquery5.Connection = con;
sqlquery5.ExecuteNonQuery();
hoeveel1 = hoeveel1 - 1;
countrij = countrij - 4;
}
}
else
{
hoeveel = ((countrij - hoeveel2) / 4) + 1;
hoeveel1 = hoeveel;
for (int i = 0; i < hoeveel; i++)
{
SqlCommand sqlquery5 = new SqlCommand("UPDATE TOP (" + countrij + ") Kist SET Stapel ='" + hoeveel1 + "' WHERE Rij ='" + rij + "'");
sqlquery5.CommandType = System.Data.CommandType.Text;
sqlquery5.Connection = con;
sqlquery5.ExecuteNonQuery();
hoeveel1 = hoeveel1 - 1;
countrij = countrij - hoeveel2;
hoeveel2 = 4;
}
}
To automatically do something in a database when UPDATE, DELETE or INSERT command is executed for a given table you have to use CREATE TRIGGER to define a new trigger.
For more information just read about usage of triggers in your specific database server. For example for SQL Server you can read this.
Unfortunately I inserted a date as dd-mm-yyyy in sql but it assumed it as mm-dd-yyyy Now more than 50 fields are like this how can I change this? I found an exception as invalid date when I was taking report by date that more than 12. Now I want to change all of the inserted fields without losting it
UPDATE tableName
SET dateColumn = MONTH(dateColumn) + "-" + DAY(vdateColumn) + "-" + YEAR(dateColumn)
I hope this work even though I didn't test it myself. Please use a WHERE clause to limit the update only to the impacted rows.
UPDATE yourTable
SET yourDateColumn = Convert(datetime,yourDateColumn,101)
Let me know if this fixes your issue.
Nothing worked but finally I reset it manually by c# console
Console.WriteLine("Changing Orderdate");
Console.WriteLine("~~~~~~~~~~~~~~~~~~");
List<string> date = new List<string>();
List<string> no = new List<string>();
int i = 0;
SqlCommand cmd = new SqlCommand("select DATEPART(yyyy,orderdate) as y, DATEPART(mm,orderdate) as m, DATEPART(dd,orderdate) as d, bno from bill", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
date.Add(dr["y"].ToString() + "-" + dr["d"].ToString() + "-" + dr["m"].ToString());
no.Add(dr["bno"].ToString());
}
con.Close();
foreach (var a in date)
{
Console.WriteLine("Inserting: " + date[i] + " With " + no[i]);
SqlCommand cmd2 = new SqlCommand("update bill set orderdate = '" + date[i] + "' where bno = " + no[i], con);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
i++;
}
Console.WriteLine("Order date changing completed \n\n");
Thank you for sharing your precious time thanks friends
In c# Windows Forms:
I'm having trouble adding a sql query result as text to a ToolStripMenuItem.Text.
The ToolStripMenuItem title should be, the company + how many orders there are in the sql table for this company which should update every x secounds.
Every 5 seconds it adds the query result to the text. My problem is that is "adds" it.
After the first 5 seconds it looks OK "rexton 1" but 5 seconds after it shows "rexton 1 1" and so on...
Here is my code:
//Rexton ordre klar til bestilling
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
command.CommandText = "SELECT COUNT(*) from bestillinger WHERE firma = #rexton and udlevering BETWEEN #date and #dateadd";
command.Parameters.AddWithValue("#bernafon", "Bernafon");
command.Parameters.AddWithValue("#gn_resound", "GN Resound");
command.Parameters.AddWithValue("#oticon", "Oticon");
command.Parameters.AddWithValue("#phonak", "Phonak");
command.Parameters.AddWithValue("#rexton", "Rexton");
command.Parameters.AddWithValue("#siemens", "Siemens");
command.Parameters.AddWithValue("#widex", "Widex");
con.Open();
command.ExecuteNonQuery();
string result = command.ExecuteScalar().ToString();
con.Close();
if (result != "0")
{
rextonToolStripMenuItem.Text = rextonToolStripMenuItem.Text + " " + result;
rextonToolStripMenuItem.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1919");
}
it is because you are setting rextonToolStripMenuItem.Text to rextonToolStripMenuItem.Text + " " + result which is appending to previous text
either set text to blank and set it again or just say
rextonToolStripMenuItem.Text = "rexton " + result
I try to prevent SQL injection in SQL query. I used following code to do it but unfortunately I faced some problem. The query is not running in oracle DB:
strQuery = #"SELECT PASSWORD FROM IBK_USERS where upper(user_id) =upper(:UserPrefix) AND user_suffix=:UserSufix AND STATUS_CODE='1'";
//strQuery = #"SELECT PASSWORD FROM IBK_CO_USERS where user_id = '" + UserPrefix + "' AND user_suffix='" + UserSufix + "' AND STATUS_CODE='1'";
try
{
ocommand = new OracleCommand();
if (db.GetConnection().State == ConnectionState.Open)
{
ocommand.CommandText = strQuery;
ocommand.Connection = db.GetConnection();
ocommand.Parameters.Add(":UserSufix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserSufix"].Value = UserSufix;
ocommand.Parameters.Add(":UserPrefix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserPrefix"].Value = UserPrefix.ToUpper();
odatareader = ocommand.ExecuteReader();
odatareader.Read();
if (odatareader.HasRows)
{
Your parameters shouldn't contain the semicolon :. This is just an indicator in your query that the variable that follows is a parameter, but you don't have to supply that on the .NET side:
ocommand.Parameters["UserSufix"] = ...
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);
}