How to compare textbox value with the sql database value in c#? - sql-server-2008

How to compare textbox value with the sql database value in c#?
im a beginner n i have to make a project. i only know how to connect sql database with the c# project.
and also tell me any tutorial, link or anything that can help me.

Here is a code sample that will assist you with this. Of course you can embelish on this as much as necessary but it will provide you the basics -- given the data that I have from your question.
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Please enter a value into the text box.");
this.textBox1.Focus();
return;
}
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
connectionStringBuilder.DataSource = ".";
connectionStringBuilder.InitialCatalog = "TEMP";
connectionStringBuilder.IntegratedSecurity = true;
SqlConnection connection = new SqlConnection(connectionStringBuilder.ToString());
SqlCommand command = new SqlCommand("SELECT Column1 FROM TableA WHERE PKColumn = 1", connection);
connection.Open();
string value = command.ExecuteScalar() as string;
connection.Close();
if (textBox1.Text.Equals(value))
{
MessageBox.Show("The values are equal!");
}
else
{
MessageBox.Show("The values are not equal!");
}
If you have some other specifics regarding this question I can probably give you a more specific example.

Related

Error when using textbox values inside string sql

"Select item from table1 where Spare parts='"+ textbox1.text+"'".
I have tried to replace item with Textbox2.text.
I used :
"Select'"& textbox2.text& "' from table1 where Spare parts='"+ textbox1.text+"'"
I got error.
I used "+ textbox2.text+" I got error too
What you have here is one of the fastest ways out there to get your app hacked. It is NOT how you include user input in an SQL statement.
To explain the right way, I also need to include the connection and command objects for context, so I may also have a different pattern for how I handle these than you're use to. I'm also assuming the mysql tag in the question is accurate (though I have my doubts), such that the correct code looks more like this:
string SQL = "Select item from table1 where `Spare parts`= #SpareParts";
using cn = new MySqlConnection("connection string here")
using cmd = new MySqlCommand(SQL, cn)
{
cmd.Parameters.AddWithValue("#SpareParts", TextBox1.Text);
cn.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// ...
}
}
}
Note the backticks around Spare Parts, so it will be correctly treated as a single object name by MySql.

How to read from MySQL table Polygon data

I am developing an application that I need location data to be stored on MySQL table. In addition to point locations, I need regions (polygon) as well.
I am currently writing the polygon coordinates as follow :
oMySQLConnecion = new MySqlConnection(DatabaseConnectionString);
if (oMySQLConnecion.State == System.Data.ConnectionState.Closed || oMySQLConnecion.State == System.Data.ConnectionState.Broken)
{
oMySQLConnecion.Open();
}
if (oMySQLConnecion.State == System.Data.ConnectionState.Open)
{
string Query = #"INSERT INTO region (REGION_POLYGON) VALUES (PolygonFromText(#Parameter1))";
MySqlCommand oCommand = new MySqlCommand(Query, oMySQLConnecion);
oCommand.Parameters.AddWithValue("#Parameter1", PolygonString);
int sqlSuccess = oCommand.ExecuteNonQuery();
oMySQLConnecion.Close();
oDBStatus.Type = DBDataStatusType.SUCCESS;
oDBStatus.Message = DBMessageType.SUCCESSFULLY_DATA_UPDATED;
return oDBStatus;
}
After the execution, I see the Blob in MySQL table.
Now I want to read the data back for my testing and it does not work the way I tried below :
if (oMySQLConnecion.State == System.Data.ConnectionState.Open)
{
string Query = #"SELECT REGION_ID,REGION_NICK_NAME,GeomFromText(REGION_POLYGON) AS POLYGON FROM region WHERE REGION_USER_ID = #Parameter1";
MySqlCommand oCommand = new MySqlCommand(Query, oMySQLConnecion);
oCommand.Parameters.AddWithValue("#Parameter1", UserID);
using (var reader = oCommand.ExecuteReader())
{
while (reader.Read())
{
R_PolygonCordinates oRec = new R_PolygonCordinates();
oRec.RegionNumber = Convert.ToInt32(reader["REGION_ID"]);
oRec.RegionNickName = reader["REGION_NICK_NAME"].ToString();
oRec.PolygonCodinates = reader["POLYGON"].ToString();
polygons.Add(oRec);
}
}
int sqlSuccess = oCommand.ExecuteNonQuery();
oMySQLConnecion.Close();
return polygons;
}
It returns an empty string.
I am not sure if I am really writing the data since I can not read Blob.
Is my reading syntax incorrect?
** Note:** I am using Visual Studio 2017. The MySQL latest version with Spacial classes.
Any help is highly appreciated.
Thanks
GeomFromText() takes a WKT (the standardized "well-known text" format) value as input and returns the MySQL internal geometry type as output.
This is the inverse of what you need, which is ST_AsWKT() or ST_AsText() -- take an internal-format geometry object as input and return WKT as output.
Prior to 5.6, the function is called AsWKT() or AsText(). In 5.7 these are all synonyms for exactly the same function, but the non ST_* functions are deprecated and will be removed in the future.
https://dev.mysql.com/doc/refman/5.7/en/gis-format-conversion-functions.html#function_st-astext
I don't know for certain what the ST_ prefix means, but I assume it's "spatial type." There's some discussion in WL#8055 that may be of interest.

comboBox without duplicated values - Visual Studio 2013 C++ and MySql

I have a 0 error program that consists in a visual studio windows form c++ connected to mysql. everything works fine!
The thing is: i have a comboBox that gets the info from the column i want, but that column is not a primary key, so it has duplicated or more values.
How can i show only one value of each in the comboBox?
Ty all !
COMBOBOX CODE:
private: void Fillcombo(void) {
String^ constring = L"datasource=127.0.0.1;port=3306;username=root;password=12345";
MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
MySqlCommand^ cmdDataBase = gcnew MySqlCommand("select * from batcel.maq_corte;", conDataBase);
MySqlDataReader^ myReader;
try{
conDataBase->Open();
myReader = cmdDataBase->ExecuteReader();
while (myReader->Read()){
String^vResponsavel;
vResponsavel = myReader->GetString("id_responsavel");
comboBox2->Items->Add(vResponsavel);
Or you can modify SQL request:
select * from batcel.maq_corte group by id_responsavel
I'm not quite familiar with the c++ cli syntax but I can give you the solution here.
You can use a list container to store the values from the column. But before inserting a value find whether the value exists in the list. If not insert the value and display it in the combobox.
e.g..
//This is just a pseudo code
list(string) somelist;
while (read){
String value;
value= read->GetString("id_responsavel");
if(! somelist.find(value)
{
somelist.insert(value);
combobox.add(value);
}

How to check for a null value in database

I am working in asp.net. I want that if the user has not uploaded his profile picture then he should be redirected to a 'profile picture uploading page'. For this we must check the database to see if that user's User_ID exists. If it doesn't exist in the database it means he has not uploaded yet. Otherwise it means he has already uploaded a picture and the page loads all of the user's information. I have a table for saving display picture:
Table: ProfilePic
Columns= ID DP User_ID
To check whether his user_id exists in the database, I use this code:
str = "select * from ProfilePic where Profile_ID=" + userid + ";";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader["Profile_ID"] != DBNull.Value)
{
LoadInfo();
LoadData();
}
else
{
Response.Redirect("DP.aspx");
}
But it's still saying "Invalid attempt to read when no data is present".
How do I resolve this problem?
You can check the reader for rows like the following example:
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
You say, "if that user's User_ID is not existing in the database it means he has not uploaded yet." That means when you run your query, it will either return a record or it won't. If it doesn't, looking for a null value in one of the fields is doomed to failure.
I see from Bjorn's answer that SqlDataReader has a HasRows property. Use it.
First of all, avoid:
Select * ...
when all you want to do is check if a particular value exists or not in a particular table. It has no benefit with respect to what about you're looking for and isn't good from a performance standpoint as well.
Now, coming to your question, there is no use of select * from. All you need to know is if a userID exists in a table or not. You see, this is a true or false scenario. Your query should also be designed to reflect this. So, essentially your query itself should return true or false and based on that you should be able to apply your business rules. You can also make use of just SELECT COUNT(). So here's the way I'd suggest to design your query:
string str = "SELECT CAST(COUNT(Profile_Id) AS bit) As 'DoesUserIDexist' FROM ProfilePic WHERE Profile_Id = 4";
You can also make use of:
string str = "SELECT COUNT(Profile_Id) As 'DoesUserIDexist' FROM ProfilePic WHERE Profile_Id = 4";
Also, its always a good practice to make use of try catch when you need to read from the database.
Essentially, your code can simplified so much as to this:
string query = "SELECT CAST(COUNT(Profile_Id) AS bit) As 'DoesUserIDexist' FROM ProfilePic WHERE Profile_Id = 4";
cmd = new SqlCommand(query, con);
try
{
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
LoadInfo();
LoadData();
}
else
{
Response.Redirect("DP.aspx");
}
}
catch
{
//Your exception handling mechanism here
}
finally
{
//Dispose your ADO.NET related objects here
}

Trouble with returning results from MySql

Edit: I solved my problem but if you have anything to add please do. Thanks
Note: I did not create the DB it was created by Wordpress hosted on GoDaddy with my site
I have a MySql Database called "wordpress" (for clarity). I want to be able to grab the most recent post from my blog and show it on the landing page for my url.
So my thought is this: connect to the MySql DB, run a query to grab the most recent post, display the post.
I built a class to handle the connection and process the request:
public class DAL
{
private string connectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=[server here]; PORT=[port]; DATABASE=wordpress;
USER=[user name here]; PASSWORD=[password here];";
private OdbcConnection blogConnection;
public DAL()
{
blogConnection = new OdbcConnection(connectionString);
}
public String[] GetRecentPost()
{
string queryString = "SELECT * FROM RecentPost";
String[] recentPost = new String[3];
//ODBC
blogConnection.Open();
OdbcCommand MySqlDB = new OdbcCommand(queryString, blogConnection);
OdbcDataReader reader = MySqlDB.ExecuteReader();
while (reader.NextResult())
{
recentPost[0] = reader.GetString(0);
recentPost[1] = reader.GetString(1);
}
recentPost[2] = reader.HasRows.ToString();
blogConnection.Close();
return recentPost;
}
}
In the queryString above RecentPost is a view I created to simplify the queryString since the query was a bit long.
I already know the view works. I tested it by opening phpMyAdmin from within the GoDaddy Hosting Center and executed the query above and I got the correct result, so I don't think the query/view is wrong.
The code-behind for the landing page:
protected void Page_Load(object sender, EventArgs e)
{
DAL dataAccess = new DAL();
String[] recentPost = dataAccess.GetRecentPost();
Title.Text = recentPost[0];
Post.Text = recentPost[1];
Extra.Text = recentPost[2];
}
So when my page loads the Title and Post texts are empty and Extra.Text is False (which from the DAL is the value from reader.HasRows).
So my guess is that its connecting fine and running the query but maybe on the wrong database? I don't know.
I also tried to debug but then my code throws an error about trying to connect to database.
So my questions are: Do you see anything wrong with the connection string?
If not do you see anything else than would cause a connection to be esablished, a query to run, no exceptions thrown but no results returned?
Any one with experience trying to grab data from thier own wordpress blog?
Thanks for the help - this one has been driving me crazy.
I don't know why my original code wasn't working but I solved my issue. For anyone else having this issue here is how I changed my code (in the GetRecentPost method) and solved my problem:
DataSet ds = new DataSet();
//ODBC
blogConnection.Open();
OdbcDataAdapter MySqlDB = new OdbcDataAdapter(queryString, blogConnection);
MySqlDB.Fill(ds);
return ds.Tables[0];
So instead of an array of strings I used a DataSet. Instead of using the OdbcDataReader I used an OdbcDataAdapter and populated the DataSet with the .Fill() method from OdbcDataAdapter I then returned the first table from the DataSet to my Page_Load method.
Here is my new Page_Load():
DataTable table = dataAccess.GetRecentPost();
if (table.Rows.Count > 0)
{
Title.Text = table.Rows[0]["title"].ToString();
Post.Text = table.Rows[0]["content"].ToString();
}
else
Extra.Text = table.Rows.Count.ToString(); \\if nothing was returned ouput the 0 just to be sure
Hope this helps anyone else with this issue
And thanks for anyone who took the time to look