I have tried posting this earlier and had to delete it because the code editor did not post it correctly and incompletely. plus I had a member ask me about SQL injection.
Here's the story:
I have a page where the user can check his information before it is submitted to the database. All I want to do is look to see if that primary key is present before I submit it to avoid getting a server error.
In my page load event I have the following:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
SqlCommand oldcmd = new SqlCommand("SELECT * from dbo.registrar WHERE [MY ID] = '"+ID+"'", conn);
oldcmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(oldcmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count >= 1)
{
lblExists.Visible = true;
lblExists.ForeColor = System.Drawing.Color.Red;
lblExists.Text = "Oops! Our records show that you have already signed up for this service. Please check your information or contact your administrator for further assistance.";
}
The label fires even though there is no record in the database which tells me that I am doing it wrong.
Try this.
SqlCommand oldcmd = new SqlCommand("SELECT COUNT(*) from dbo.registrar WHERE [MY ID] = #id", conn);
oldcmd.Parameters.Add("#id", SqlDbType.Int);
oldcmd.Parameters["#id"].Value = ID;
if ((int)oldcms.ExecuteScalar() >= 1)
{
lblExists.Visible = true;
lblExists.ForeColor = System.Drawing.Color.Red;
lblExists.Text = "Oops! Our records show that you have already signed up for this service. Please check your information or contact your administrator for further assistance.";
}
else
{
lblExists.Visible = false;
}
Related
i'm creating a recipe website for meals. I make an admin panel and i want to delete a meal which i added before. And there is a menu which includes number of the meal. For example there are 4 meals in pasta category and it shows Pasta(4) at mainpage.
Me as an admin, if i would like to add a new meal to my website, it's working. I select a category and it's adding to that category. But for deleting, it's working wrong. It always delete the first value in DropDownList which is Meat Foods. Can you help me to find an answer?
Here is the code:
if (Page.IsPostBack == false)
{
id = Request.QueryString["YemekId"];
islem = Request.QueryString["islem"];
SqlCommand komut2 = new SqlCommand("Select *from Kategoriler", baglan.baglanti());
SqlDataReader oku2 = komut2.ExecuteReader();
DropDownList1.DataTextField = "KategoriAd"; //DropDownList'e kategorilerin adlarını text biçiminde oldukları için bu şekilde çektik.
DropDownList1.DataValueField = "KategoriId"; //DropDownList'e kategorilerin id nolarını value değerinde oldukları için bu şekilde çektik.
DropDownList1.DataSource = oku2;
DropDownList1.DataBind();
SqlCommand komut = new SqlCommand("Select *from Yemek", baglan.baglanti());
SqlDataReader oku = komut.ExecuteReader();
DataList1.DataSource = oku;
DataList1.DataBind();
}
//silme işlemi
if (islem == "sil")
{
SqlCommand komutsilme = new SqlCommand("Delete from Yemek where YemekId=#s1", baglan.baglanti());
komutsilme.Parameters.AddWithValue("#s1", id);
komutsilme.ExecuteNonQuery();
baglan.baglanti().Close();
SqlCommand kategorisil = new SqlCommand("Update Kategoriler set KategoriAdet=KategoriAdet-1 where KategoriId=#k1", baglan.baglanti());
kategorisil.Parameters.AddWithValue("#k1", DropDownList1.SelectedValue);
kategorisil.ExecuteNonQuery();
baglan.baglanti().Close();
Response.Write("<script> alert('Yemek başarıyla silindi!')</script>");
}
you are passing a id as a string from your query string to the parameter
komutsilme.Parameters.AddWithValue("#s1", id);
I am assuming YemekId is an int in your database so try this
komutsilme.Parameters.AddWithValue("#s1", int.Parse(id));
AddWithValue will derive the type of the parameter of its value, so ensure that it's the correct type, in this case int not string.
I am trying to create a login form with MySQL connection and i have so far done well but am having trouble with one part where I get this error is VS2019
cannot convert from 'object' to 'MySql.Data.MySqlClient.MySqlDbType'
This is the code im using in an array
private bool ButtonLogin_Click(object sender, EventArgs e)
{
DB db = new DB();
String username = textBoxUsername.Text;
String password = textBoxPassword.Text;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM `users` WHERE `username` = #usn and 'password' = #pass");
command.Parameters.Add("#usn", VarChar).Value = textBoxUsername.Text;
command.Parameters.Add("#pass", VarChar).Value = textBoxPassword.Text;
adapter.SelectCommand = command;
adapter.Fill(table);
// check if this username already exists in the database
if (table.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
The error I am getting is with the VarChar part it doesn't seem to recognize VarChar.. everything else seems to be recognised but not VarChar... please help. I have tried googling the error and trying the solutions mentioned like ("#usn", VarChar, 15) and nothing is actually making VarChar a recognized MySQL object.
Let try with AddWithValue to resolve your issue.
command.Parameters.AddWithValue("#usn", textBoxUsername.Text);
command.Parameters.AddWithValue("#pass", textBoxPassword.Text);
I am coding win form app, which checks on startup right of the currently logged user. I had these right saved in MS SQL server in the table. When importing data to Datatable, there is no problem. But when I want to read value, there is message "cannot find column xy".
SqlDataAdapter sdaRights = new SqlDataAdapter("SELECT * FROM rights WHERE [user]='" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "'", conn);
DataTable dtRights = new DataTable(); //this is creating a virtual table
sdaRights.Fill(dtRights);
Object cellValue = dt.Rows[0][1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
I would like, that program would save the value from SQL to int.
You are assuming that you have rows being returned, would be my first guess. You should loop through your DataTable instead of simply trying to access element 0 in it.
DataTable dtRights = new DataTable();
sdaRights.Fill(dtRights);
foreach(DataRow row in dtRights.Rows) {
Object cellValue = row[1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
}
using (SqlConnection con = new SqlConnection("your connection string"))
{
using (SqlCommand cmd = new SqlCommand("SELECT [column_you_want] FROM [rights] WHERE [user] = #user"))
{
cmd.Parameters.AddWithValue("#user", System.Security.Principal.WindowsIdentity.GetCurrent().Name);
con.Open();
int right = Convert.ToInt32(cmd.ExecuteScalar());
}
}
I try researching this everywhere but it appears when I run my windows form application and display my database. Each it keeps automatically skipping and adding rows.
Here is a screen shot of my gridview
Here is also my code where it displays the database when I click a button:
try
{
conn = new MySqlConnection();
conn.ConnectionString = connstring;
query = "INSERT INTO schedule(name) VALUES(#namevalue)";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#namevalue", this.nameEmp.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Connection Success");
myadapt = new MySqlDataAdapter();
string sq = "SELECT * FROM schedule";
myadapt.SelectCommand = new MySqlCommand(sq, conn);
tb = new DataTable();
myadapt.Fill(tb);
BindingSource src = new BindingSource();
src.DataSource = tb;
dataGridView1.DataSource = src;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Do you mean you want to show those rows which name column is not empty?
Gridview can just show the table you query from the DB,so you can change the SQL code to get the right table,
for example:change SELECT * FROM schedule to SELECT * FROM schedule WHERE schedule(name) IS NOT NULL.
actually, I figured it out. I had in that code above the statement
INSERT twice in my program. I removed it and redid my database on my server and fixed the problem. So sorry for the trouble.
I am loading my table from mysql and I want to make first column link. I mean link to another form. I want to display student details and when click on a name program will open a new form and display all info about student. Anyone have any idea about how to do?
DataTable table = new DataTable();
MySqlDataAdapter adapsql = new MySqlDataAdapter("SELECT name, surname, dob, sex, nationality, mobile, notes FROM student", connection);
adapsql.Fill(table);
dataGridView1.DataSource = table;
int x = (dataGridView1.RowCount)-1;
label21.Text = Convert.ToString(x);
cmd = connection.CreateCommand();
cmd.CommandText = #"SELECT * FROM reservation";
MySqlDataReader Reader = cmd.ExecuteReader();
if (!Reader.HasRows) return;
while (Reader.Read())
{
reservation.Add(Convert.ToInt16(GetDBString("roomID", Reader)));
}
Reader.Close();
You can handle this under the following event:
dataGridView1_CellClick
Get the CurrentCell value of the datagridiview and use this information to open your second form and add the required information to the fields you have there.
Sample code:
if (this.dataGridView1.CurrentCell != null)
{
string valueofcell=dataGridView1.CurrentCell.Value.ToString();
// Raise the corresponding form as per you required
}