I have problem I can't able to load data into textboxes that the query fetch from database in windows form. The while loop cannot execute. how to solve this issue. or not have any error or exception. The inner commands cannot execute the debugger move to catch and finish.
private void btnCheck_Click(object sender, EventArgs e)
{
try
{
// query = "SELECT Id, Emplname, CNIC, City, MobileNo, Address, Salary, DailyWage, CompanyId, Status FROM Employees where id = '" + labCompyId.Text + "'";
query = "SELECT CNIC, City, MobileNo, Address, Salary, DailyWage, Status FROM Employees WHERE (EmployId = '"+txtEmployId+"') AND (Emplname = '"+txtEmplyName+"')";
SqlCommand command1 = DBConnectivity.getCommandForQuery(query, connection);
SqlDataReader reader1 = command1.ExecuteReader();
while(reader1.Read())
{
this.txtCNIC.Text = (reader1["CNIC"].ToString());
this.txtEmplyCity.Text = (reader1["City"].ToString());
this.txtEmplyAddress.Text = (reader1["Address"].ToString());
this.txtSalary.Text = (reader1["Salary"].ToString());
this.txtDailyWage.Text = (reader1["DailyWage"].ToString());
reader1.Close();
}
}
catch (Exception ex)
{
}
}
Oh what.Stop!!! Use Parameterized query to avoid SQL Injection
Mention you conncection string in connection
I hope the problem is you have missesd txtEmployId.Text value and txtEmplyName.Text value in your select query
SqlConnection connection= new SqlConnection(your Connection string);
string query = "SELECT CNIC, City, MobileNo, Address, Salary, DailyWage, Status
FROM Employees WHERE EmployId =#EmpID AND Emplname = #Emplname ";
SqlCommand command1 = new SqlCommand(query, connection);
connection.Open();
command1.Parameters.AddWithValue("#EmpID",txtEmployId.Text);
command1.Parameters.AddWithValue("#Emplname",txtEmplyName.Text);
SqlDataReader reader1 = command1.ExecuteReader();
while(reader1.Read())
{
this.txtCNIC.Text = (reader1["CNIC"].ToString());
this.txtEmplyCity.Text = (reader1["City"].ToString());
this.txtEmplyAddress.Text = (reader1["Address"].ToString());
this.txtSalary.Text = (reader1["Salary"].ToString());
this.txtDailyWage.Text = (reader1["DailyWage"].ToString());
reader1.Close();
}
Where is your connectionstring? If it is not in the page, include one.
Open the connection like Con.open()
Use parameterized query to avoid sql injection but that is just a suggestion.
The problem of the code is the connection string in my opinion.Open the connection inside the try block.
Related
When I run this query I get the following error:
Syntax error(missing operator) in query expression '[Customer] = 'O'SMILE' and [Product] = 'Casserole(20kg)
Code:
// When print button is executed database operations
// Load data from database based upon select query
String codeQuery = "SELECT count(*) FROM [sheet1$] WHERE [Customer] = '" + lblcustomername.Text + "' and [Product]='" + lblproductname.Text + "'";
OleDbConnection Connection;
Connection = new OleDbConnection(OutputDatabaseConnectionString);
OleDbCommand Command = new OleDbCommand(codeQuery, Connection);
Command.Connection = Connection;
try
{
Connection.Open();
count = (Int32)Command.ExecuteScalar();
Connection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
The error is because of the unquoted single quote "'" in the name O'SMILE and your use of string concatenation, rather than using a parameterised query. It also indicates that you are vulnerable to SQL injection attacks.
You must use Parameters!
string sql = "SELECT count(*) FROM [sheet1$] WHERE [Customer] = #customer and [Product] = #product";
using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("customer", SqlDbType.VarChar, 100).Value = lblcustomername.Text;
cmd.Parameters.Add("product", SqlDbType.VarChar, 120).Value = lblproductname.Text;
count = (Int32)command.ExecuteScalar();
}
enter image description hereI'm trying to show all my items on a combobox, but when y run my app I only get one item. Can you help me please, here's my code
try
{
MySqlConnection conection = new MySqlConnection("server = 127.0.0.1; database = sistemalaboratorio; Uid = root; pwd =;");
string selectQuery = "SELECT clavemateria FROM materia";
conection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, conection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read());
{
comboBox1.Items.Add(reader["clavemateria"].ToString());
}
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Assuming this read is happening before the page loads the combobox, make sure your materia table has more than 1 record in it.
These queries might usful to count the records in your SQL table in case you dont have direct access using SQL Management studio
SELECT COUNT(*) FROM materia WITH (NOLOCK)
-- NOLOCK here is for testing for this answer: no more, no less
or
SELECT clavemateria, count(*)
FROM materia
GROUP BY clavemateria
Also you can try this:
string qr1 = "select * from materia ";
SqlCommand cmd1 = new SqlCommand(qr1, con);
con.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
cmbcat.Items.Clear();
while (dr1.Read())
{
cmbcat.Items.Add(new Item(dr1["clavemateria"].ToString(), dr1["clavemateria"].ToString()));
}
con.Close();
Or refer to this example
I've tried running the code and I have no idea what's wrong with the query. Because it keeps saying invalid column name, when I'm trying to retrieve the data from that column instead. The column name matches the one in the DB. It's well connected because it's connected to a login form where it detects the other given password and name. I'm using based on a search textbox.
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDetailConnectionString"].ToString());
try
{
cnn.Open();
SqlCommand command = new SqlCommand();
command.Connection = cnn;
string query = "SELECT *FROM AffiliatedRegister WHERE Username=" + txtUser.Text + "";
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
---[Converting String from db /Insert to textboxes]---
}
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You need to wrap the username text in quotes.
Your emitted sql script is gonna look like:
SELECT *FROM AffiliatedRegister WHERE Username=InputUserName
So SQL is trying to compare the column Username to the column InputUsername.
Once you wrap the user name in quotes, it would be:
SELECT *FROM AffiliatedRegister WHERE Username='InputUserName'
Your statement erred because you did not wrap your string in quotes so Sql interpeted it as on object and not a string. That being said there you should use parameters and not string concatenation.
Use parameters
Wrap your SqlConnection in a using block
You should specify the column order in the SELECT statement, do not use *.
Do not swallow an Exception unless you know how to recover from it
Update code
private void btnSearch_Click(object sender, EventArgs e)
{
// use ConnectionString property
// wrap in using block
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDetailConnectionString"].ConnectionString))
{
try
{
SqlCommand command = new SqlCommand();
command.Connection = cnn;
// use parameters
// avoid *, specify columns instead
string query = "SELECT * FROM AffiliatedRegister WHERE Username= #userName";
command.CommandText = query;
// use parameters, I assumed the parameter type and length - it should be updated to the type and length specified in your table schema
command.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar, 200) {Value = txtUser.Text });
// open as late as possible
cnn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// ---[Converting String from db / Insert to textboxes]-- -
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
// do not swallow the exception unless you know how to recover from it
throw;
}
}
}
Well first of all your query is very dangerous so please don't use it for production purpose.
Now what you need to do :-
In your query you need single quotes around the txtUser.Text.
Like this :-
"SELECT *FROM AffiliatedRegister WHERE Username='" + txtUser.Text
+ "'";
Resulting query : SELECT *FROM AffiliatedRegister WHERE Username = 'txtUser.Text';
You can also put double quotes like :-
...Username=\"" + txtUser.Text + "\"";
its complicated ;-) Earlier one is better for the reading purpose.
Why it did not run?
Because all values except integers must be passed inside single or double quotes in a query. Like :-
SELECT * FROM TABLE_NAME WHERE TABLE_NAME.COLUMN_NAME = "VALUE";
Now one very important thing please don't use these kinds of queries for production purpose. I guess you are in development phase so answering this question is not gonna ruin your life ...!!!
You can try to replace the your string: string query = "SELECT *FROM AffiliatedRegister WHERE Username=" + txtUser.Text + "";
to: string query = "SELECT <yourcolumn> FROM AffiliatedRegister WHERE Username=" + txtUser.Text + "";
I believe it is necessary to specify the column name.
Best regards
After spending several hours i am unable to figure out that why null values are being inserted into mySQL table using ASP.NET web page. I am using odbc connector for this.Below is the code for the same.
public int Insert(string FirstName, string LastName, int age)
{
OdbcConnection conn = new OdbcConnection(connStr);
conn.Open();
OdbcCommand odcmd_Insert = new OdbcCommand("INSERT INTO webuse(firstName,lastName,age) VALUES(#param1,#param2,#param3)",conn);
odcmd_Insert.Connection = conn;
odcmd_Insert.CommandType = System.Data.CommandType.Text;
try
{
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param1", FirstName));
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param2", LastName));
odcmd_Insert.Parameters.Add( new OdbcParameter("#param3", age));
return odcmd_Insert.ExecuteNonQuery();
}
catch (OdbcException e)
{
throw;
}
finally {
odcmd_Insert.Dispose();
conn.Close();
conn.Dispose();
}
}
I have debugged the code and all things seems well but all columns are updated with null values. Please help i am a noob to ASP.NET.
Please try your argument like as below. I have used the MySqlConnection. you can use ODBC connection as well.
try
{
// Connection string for a typical local MySQL installation
string cnnString = "Server=localhost;Port=3306;Database=ci_series;Uid=root;Pwd=";
// Create a connection object
MySqlConnection connection = new MySqlConnection(cnnString);
// Create a SQL command object
string cmdText = "INSERT INTO webuse(firstName,lastName,age) VALUES(?param1,?param2,?param3)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("?param1", MySqlDbType.VarChar).Value = firstName;
cmd.Parameters.Add("?param2", MySqlDbType.VarChar).Value = lastName;
cmd.Parameters.Add("?param3", MySqlDbType.VarChar).Value = age;
connection.Open();
int result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
The command should be as
string cmdText = "INSERT INTO webuse(firstName,lastName,age) VALUES(?param1,?param2,?param3)";
I think that your OdbcCommand should be (replace in query #paramN with ?)
OdbcCommand odcmd_Insert = new OdbcCommand("INSERT INTO webuse(firstName,lastName,age) VALUES(?,?,?)",conn);
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param1", FirstName));
odcmd_Insert.Parameters.Add(new OdbcParameter( "#param2", LastName));
odcmd_Insert.Parameters.Add( new OdbcParameter("#param3", age));
Instead of the parameter it takes a ? in the CommandText (leave the name in the actual parameters param1,param2,param3)
I am trying to query SQL Server database from C#
I have class
Class_A
{
public fetch((string name, string last_name))
{
SqlConnection conn = null;
double val = 0;
string server = "123.444.22.sss";
string dbase = "xyz";
string userid = "cnsk";
string password = "xxxxxx";
string connection = "Data Source=" + server + ";Initial Catalog=" + dbase
+ ";User ID=" + userid + ";Password=" + password;
conn = new SqlConnection(connection);
try
{
conn.Open();
}
catch(Exception)
{
string e = "Database error contact administrator";
MessageBox.Show(e, "Error!");
}
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table where NAME"
+ " = name and LAST_NAME = last_name", conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
//do something
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return (0);
}
}
There is a problem in my query.
When I give normal query "select * from table" --- this gives me perfect results.
But when I try to give where condition it gives me error. Any suggestions, to fix this?
Thanks.
Use a parameterised query, and more usings, and stop with the generic exceptions.
something like this where somName and SomeLastName are the values that you wan t to query for.
String sql = "Select * From SomeTable Where [Name] = #Name and [Last_Name] = #LastName";
try
{
using(SqlConnection conn = new SqlConnection(connection))
{
conn.Open();
using( SqlCommand command = new SqlCommand(sql,conn))
{
command.Parameters.Add(new SqlParameter("Name", DbType.String,someName));
command.Parameters.Add(new SqlParameter("LastName", DbType.String,someLastName));
using(IDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
//do something
}
}
}
}
return 0; // Huh?
}
catch(SqlException sex)
{
Console.Writeline(String.Format("Error - {0}\r\n{1}",sex.Message, sex.StackTace))
}
NB not checked might be a silly in it
⚠️ WARNING This answer contains a SQL injection security vulnerability. Do not use it. Consider using a parameterized query instead, as described in some of the other answers to this question (e.g. Tony Hopkinson's answer).
Try adding quotes around the values in the where clause like this:
select * from table where NAME = 'name' and LAST_NAME = 'last_name'
In your case where you are using variables you need to add the quotes and then concatenate the values of the variables into the string. Or you could use String.Format like this:
var sql = String.Format("select * from table where [NAME] = '{0}' and LAST_NAME = '{1}'", name, last_name);
SqlCommand myCommand = new SqlCommand(sql);
Try
select * from table where NAME = 'name' and LAST_NAME = 'last_name'
instead of
select * from table where NAME = name and LAST_NAME = last_name
Edit:
If name and last_name are your parameters then try this:
SqlCommand myCommand = new SqlCommand("select * from table where NAME = #name and LAST_NAME = #last_name", conn);
myCommand.Parameters.AddWithValue( "#name", name );
myCommand.Parameters.AddWithValue( "#last_name", last_name );
Using parameterized commands means that you are invulnerable to a potential huge security hole - sql injection which is possible when command text is manually concatenated.
The text needs to be quoted as others have said--but that's not really the right answer here. Even without malice you're going to run into trouble with the Irish here, look what happens when you try to look for Mr. O'Neill. Use parameters instead.