C# ODBC mysql (null output) - c#

can anyone help me? i am getting null output. though data exists in database.
string retrivenp = "select emp_email from E_details where emp_ID ='" + c_c +
"'AND emp_name = '" + s_s + "'AND emp_address = '" + n_n +
"'AND Date_joining = '" + Calendar1.SelectedDate + "'";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.ToString();
Label1.Text = url_path.ToString();
}
}
}

i think the string with many quotes is the problem when it will be executed it may give the wrong query
use command parameters it's better
string retrivenp = "select emp_email from E_details where emp_ID = ? AND emp_name = ? AND emp_address = ? AND Date_joining = ?";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
comm1.Parameters.Add("#p1", OleDbType.Int).Value = c_c;
comm1.Parameters.Add("#p2", OleDbType.Text).Value = s_s;
comm1.Parameters.Add("#p3", OleDbType.Text).Value = n_n;
comm1.Parameters.Add("#p4", OleDbType.Date).Value = Calendar1.SelectedDate;
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.GetString(0);
Label1.Text = url_path.ToString();
}
read.Close();
}
}

Related

Need to find ID number from database using string in c#

I need to get data from label which i had got back from previous page using Sessions from that label i need to use it to find ID for that data for example if Label contain word 'IT' it need to find its ID in database D_ID=5 code is given below
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to this line
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
See the single quotes in the second line. Your string value is not in single quotes and this is the reason.
EDIT: Your code is open for SQL Injection Attack. You should use the SqlParameter instead of concatenating the query.
For More reading you can use this link:
http://www.w3schools.com/sql/sql_injection.asp
As simple as missing the quotations of your sql.
sql-> "where D_Name = 'somevalue'
... So the fix for your code would be
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
or faster search
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
or for search similar string change to
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";

How to do if/else statement for fileUpload

Heyy all. I am trying to do an if/else statement for my fileupload function on my Edit Profile page in my ASP.net webpage.
Here is my code:
protected void btnContinue_Click(object sender, EventArgs e)
{
//Declaration of variable to update Profile Image
string imageName, newContact;
imageName = FileUpload1.FileName.ToString();
newContact = tbMobile.Text.ToString();
username = (String)Session["NonAdmin"];
MySqlConnection mcon = new MySqlConnection("server=182.50.133.91;user id=Jonathan;password=jon123;persistsecurityinfo=True;database=ajactrac_;allowuservariables=True");
MySqlDataAdapter sda = new MySqlDataAdapter("select * from pointofcontact where Username = '" + username.ToString() + "'", mcon);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
MySqlCommand command = mcon.CreateCommand();
MySqlCommand command1 = mcon.CreateCommand();
MySqlCommand command2 = mcon.CreateCommand();
MySqlCommand command3 = mcon.CreateCommand();
MySqlCommand command4 = mcon.CreateCommand();
MySqlCommand command5 = mcon.CreateCommand();
MySqlCommand command6 = mcon.CreateCommand();
MySqlCommand command7 = mcon.CreateCommand();
command.CommandText = "update pointofcontact set Password = ?pwd where Username = '" + username.ToString() + "'";
command1.CommandText = "update pointofcontact set FirstName = ?firstname where Username = '" + username.ToString() + "'";
command2.CommandText = "update pointofcontact set LastName = ?lastname where Username = '" + username.ToString() + "'";
command3.CommandText = "update pointofcontact set ContactNumber = ?contact where Username = '" + username.ToString() + "'";
command4.CommandText = "update pointofcontact set EmailAddress = ?email where Username = '" + username.ToString() + "'";
command5.CommandText = "update pointofcontact set Address = ?address where Username = '" + username.ToString() + "'";
command6.CommandText = "update pointofcontact set BackupContactNumber = ?backupnumber where Username = '" + username.ToString() + "'";
command7.CommandText = "update pointofcontact set ProfilePic = ?newimage where Username = '" + username.ToString() + "'";
mcon.Open();
if (tbNewPassword.Text == "")
{
command.Parameters.AddWithValue("?pwd", tbOldPassword.Text.Trim());
}
else
{
command.Parameters.AddWithValue("?pwd", tbNewPassword.Text.Trim());
}
if(tbNewFirstName.Text == "")
{
command1.Parameters.AddWithValue("?firstname", tbFirstName.Text.Trim());
}
else
{
command1.Parameters.AddWithValue("?firstname", tbNewFirstName.Text.Trim());
}
if(tbNewLastName.Text == "")
{
command2.Parameters.AddWithValue("?lastname", tbLastName.Text.Trim());
}
else
{
command2.Parameters.AddWithValue("?lastname", tbNewLastName.Text.Trim());
}
if(tbNewContact.Text == "")
{
command3.Parameters.AddWithValue("?contact", tbMobile.Text.Trim());
}
else
{
command3.Parameters.AddWithValue("?contact", tbNewContact.Text.Trim());
}
if(tbNewEmail.Text == "")
{
command4.Parameters.AddWithValue("?email", tbEmail.Text.Trim());
}
else
{
command4.Parameters.AddWithValue("?email", tbNewEmail.Text.Trim());
}
if(tbNewAddress.Text == "")
{
command5.Parameters.AddWithValue("?address", tbAddress.Text.Trim());
}
else
{
command5.Parameters.AddWithValue("?address", tbNewAddress.Text.Trim());
}
if(tbNewBackupContact.Text == "")
{
command6.Parameters.AddWithValue("?backupnumber", tbBackupContact.Text.Trim());
}
else
{
command6.Parameters.AddWithValue("?backupnumber", tbNewBackupContact.Text.Trim());
}
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + imageName);
command7.Parameters.AddWithValue("?newimage", imageName);
command.ExecuteNonQuery();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command4.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
command7.ExecuteNonQuery();
mcon.Close();
string javaScript = "<script language=JavaScript>\n" + "alert('Profile Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
else
{
string javaScript = "<script language=JavaScript>\n" + "alert('Some Error Occured! Profile Not Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
tbNewPassword.Text = "";
}
I had planned to use the if else statement for my fileupload function such that if the user has not uploaded a new picture, he/she would be still able to update their profile.
Currently when I try to edit a user's profile, this error message comes out.
Before uploading files to any directory, it is good to have this statement before saving file.
if (!Directory.Exists(Server.MapPath("~/Images")))
Directory.CreateDirectory("~/Images");
add above statement before this line
FileUpload1.PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Images", imageName)));

c# Insert data into MySQL database using parameters

This probably a simple solution, but I've got a deadline to catch and I don't know the exact problem here.
So here's the deal, I'm trying to update my table using this piece of code:
private void btn_opslaan_Click(object sender, EventArgs e)
{
string opleidingsid = "Select OpleidingsID From opleidingen Where Opleidingsnaam = '" + cb_opleiding.Text + "'";
MySqlCommand cmdid = new MySqlCommand(opleidingsid, dbconnect.connection);
dbconnect.OpenConnection();
MySqlDataReader reader = cmdid.ExecuteReader();
reader.Read();
int oplid = (int)reader.GetValue(0);
cmdid.Dispose();
reader.Close();
sql = "UPDATE leerlingen SET Naam = '_naam', Adres = '_adres', Woonplaats = '_woonplaats', Postcode = '_postcode', Email = '_email', Telefoonnummer = '_telefoonnummer', Klas = '_klas', Ovnummer = '_ovnummer', OpleidingsID = '_opleidingsid', Startdatum = '_startdatum', Einddatum = '_einddatum' WHERE LeerlingID = '_leerlingid'";
// sql = "UPDATE leerlingen set Naam = '" + txt_naam.Text + "', Adres = '" + txt_adres.Text + "', Woonplaats = '" + txt_woonplaats.Text + "', Postcode = '" + txt_postcode.Text + "', Email = '" + txt_email.Text + "', Telefoonnummer = '" + txt_telefoonnumer.Text + "', Klas = '" + txt_klas.Text + "', Ovnummer = '" + txt_ovnummer.Text + "', OpleidingsID = '" + oplID + "', Startdatum = '"+mc_startdatum.SelectionStart.Date.ToString()+"', Einddatum = '"+ mc_einddatum.SelectionStart.Date.ToString() +"' WHERE LeerlingID = '" + Int32.Parse(lbl_leerlingid.Text) + "'";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect.connection);
cmd.Parameters.AddWithValue("_naam", txt_naam.Text);
cmd.Parameters.AddWithValue("_adres", txt_adres.Text);
cmd.Parameters.AddWithValue("_woonplaats", txt_woonplaats.Text);
cmd.Parameters.AddWithValue("_postcode", txt_postcode.Text);
cmd.Parameters.AddWithValue("_email", txt_email.Text);
cmd.Parameters.AddWithValue("_telefoonnummer", txt_telefoonnumer.Text);
cmd.Parameters.AddWithValue("_klas", txt_klas.Text);
cmd.Parameters.AddWithValue("_ovnummer", txt_ovnummer.Text);
cmd.Parameters.AddWithValue("_opleidingsid", oplid);
cmd.Parameters.AddWithValue("_startdatum", mc_startdatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_einddatum", mc_einddatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_leerlingid", int.Parse(lbl_leerlingid.Text));
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("opslaan gelukt");
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
throw;
}
dbconnect.CloseConnection();
this.Close();
}
I've already tried without the single quotes, it would give me the error that colomn '_leerlingid' does not exist, but that is the parameter...
Now, I dont get any errors, but it wouldn't update my database.
Any help please
P.S. Ignore the sql injection please, before this , i didn't knew better before I found out about parameters.
Try replacing your parameters with the # symbol and remove the single quotes, like this:
SQL = "UPDATE leerlingen SET Naam = #naam, Adres = #adres";
cmd.Parameters.AddWithValue("#naam", txt_naam.Text);
cmd.Parameters.AddWithValue("#adres", txt_adres.Text);
I think what you did wrong is you mustn't initialize your MySqlCommand like that. It must be like this..
MySqlCommand cmd;
cmd = dbconnect.createCommand();
cmd.CommandText = "UPDATE tableName SET firstname=#firstname, lastname=#lastname where id=#id";
cmd.Parameters.AddWithValue("#id", idTxt.Text);
cmd.Parameters.AddWithValue("#firstname", fName.Text);
cmd.Parameters.AddWithValue("#lastname", lName.Text);
cmd.ExecuteNonQuery();
when I creating a new data in c#, I make it like this ..
//values
String a = "COL1ROW1", b = "COL1ROW2";
//this is the code for mysql
String query = "Insert Into tableName(Column1, Column2)values('" + a + "','" + b + "')";
//conn is your mysqlconnection
MySqlCommand cmd = new MySqlCommand(query, conn);
//then execute it
cmd.ExecuteNonQuery();

Getting Date from database in a string

I am trying to get date from my database into a string and comparing it with the today's date to perform some operation.
What I did as a solution but still the label isn't displaying the messages.
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("Files/" + FileName));
string FilePath = "Files/" + FileName;
//SqlCommand cmd = new SqlCommand();
DAL obj = new DAL();
using (SqlConnection conn = obj.openCon())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime() ;
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if (duedate != null && today.Date > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift + "', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
}
}
You have to get DueDate from tbl_AssignmentUpload1 .
For example :
string strSQL = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like #AssignmentTitle ";
(SqlCommand myCommand = new SqlCommand(strSQL, cnn)) // Cnn is your sql connection
{
myCommand.Parameters.AddWithValue("#AssignmentTitle", AssignmentTitle );
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
DateTime today1 = Convert.ToDateTime(reader["DueDate "].ToString());
}
}
}
After this you can do your insert statement
Try something like this. Ok updated with the fix for duedate.
using (SqlConnection conn = SQL.GeSQLConnection())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime();
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if(duedate != null && DateTime.Today > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift +"', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
else
{
lbl_uploaded.Text = "No Due date was selected for the given assesment title";
}
}

Parameters supplied for object which is not a function. If the parameters are intended as a table hint, a WITH keyword is required

I'm running Windows 7 and II7 and SQL server 2008 R2 . I have an aspx program and when I try to run it I get the following error
Parameters supplied for object 'users' which is not a function. If
the parameters are intended as a table hint, a WITH keyword is
required.
What I've coded is this :
public ArrayList GetGoodsList(string type, string goodsType, string user, string payType, bool flag)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Conn"].ToString());
DataSet ds = new DataSet();
sSql = "select count(*) from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sSql;
conn.Open();
int maxRow = Int32.Parse(cmd.ExecuteScalar().ToString());
sSql = "select * from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
cmd.CommandText = sSql;
SqlDataReader reader = cmd.ExecuteReader();
ArrayList gInfos = new ArrayList();
GoodsInfo gInfo;
for (int i = 0; i < maxRow; i++)
{
if (reader.Read())
{
gInfo = new GoodsInfo();
gInfo.G_ID = Int32.Parse(reader["G_ID"].ToString());
gInfo.G_Name = reader["G_Name"].ToString();
gInfo.Type = reader["Type"].ToString();
gInfo.GoodsType = reader["GoodsType"].ToString();
gInfos.Add(gInfo);
}
}
conn.Close();
return gInfos;
}
Any idea? Thanks!
Without giving away the answer, your issue in in your SELECT statement, sSql = ...
It's not the correct SQL syntax.
Have a read of this wikipedia article on the SELECT statement.

Categories

Resources