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
}
Related
I am using qt to create a user login. I am using Sqlite as my database and am stuck for some reason it is not working properly. I was able to corectly bypass the login screen only when typing in the first row from the database. Any other user cannot log in (row 2, 3,4 ... in database). I have been reading all kinds of posts for the past days and have not come to a proper solution. Here is my code. I have also tried creating a query through QSqlQuery and passing it into the QSQlQueryModel Object which did not work at all.
void MainWindow::on_login_clicked()
{
QSqlDatabase m_db;
QString path = "C:/Users/annea/Summer2019Database.db";
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName(path);
m_db.open();
if (!m_db.open())
{
qDebug() << "Error: connection with database fail";
}
else
{
qDebug() << "Database: connection ok";
}
QString username = ui->username->text();
QString password = ui->password->text();
QSqlQueryModel *queryModel = new QSqlQueryModel;
queryModel->setQuery("SELECT * FROM [User Database] WHERE Username= username"); //select the row of where the Username == username
queryModel->query().exec(); //execute it (not really sure why or what this does
if(queryModel->record(0).value(1).toString()== password) //if a row is found check column 2 for password
{
destroy(); //destroy current window
if(queryModel->record(0).value(3).toString()== 1) //if id is equal to one log in as user
{
user.showMaximized();
}
else {
dbManager.showMaximized();
}
}
else {
qWarning("Wrong Password or Username");
}
}
I think your query is wrong. Instead of writing like this:
queryModel->setQuery("SELECT * FROM [User Database] WHERE Username= username"); //select the row of where the Username == username
You might want writing like this:
queryModel->setQuery(QString("SELECT * FROM [User Database] WHERE Username = '%1'").arg(username)); //select the row of where the Username == username
Why? Because you are writing a query, and you probably want to check against the user name entered, not the string "username". Also, don't forget apostrophes when comparing.
In order to find more information which might help with your problem, you should read Qt's documentation regarding its' classes. Also, it would be beneficial to take a look into the SQLite WHERE clause and how strings are represented when writing queries:
https://doc.qt.io/qt-5/qsqlquerymodel.html#setQuery
https://doc.qt.io/qt-5/qsqlquery.html#QSqlQuery-1
http://www.sqlitetutorial.net/sqlite-where/
https://www.sqlite.org/datatype3.html
I am using primefaces autocomplete component with pojos and which is filled from a database table with huge number of rows.
When I select value from database which contains millions of entries (SELECT synonym FROM synonyms WHERE synonym like '%:query%') it takes a very long time to find the word on autocomplete because of huge database entries on my table and it will be bigger in future.
Is there any suggestions on making autocomplete acting fast.
Limiting the number of rows is a great way to speed-up autocomplete. I'm not clear on why you'd limit to 1000 rows though: you can't show 1000 entries in a dropdown; shouldn't you be limiting to maybe 10 entries?
Based on your comments below, here is an example database query that you should be able to adapt to your situation:
String queryString = "select distinct b.title from Books b where b.title like ':userValue'";
Query query = entityManager.createQuery(queryString);
query.setParameter("userValue", userValue + "%");
query.setMaxResults(20);
List<String> results = query.getResultList();
I finally went to using an index solar for doing fast requests while my table will contains more than 4 million entries which must be parsed fastly and without consuming a lot of memory.
Here's I my solution maybe someone will have same problem as me.
public List<Synonym> completeSynonym(String query) {
List<Synonym> filteredSynonyms = new ArrayList<Synonym>();
// ResultSet result;
// SolrQuery solrQ=new SolrQuery();
String sUrl = "http://......solr/synonym_core";
SolrServer solr = new HttpSolrServer(sUrl);
ModifiableSolrParams parameters = new ModifiableSolrParams();
parameters.set("q", "*:*"); // query everything
parameters.set("fl", "id,synonym");// send back just the id
//and synonym values
parameters.set("wt", "json");// this in json format
parameters.set("fq", "synonym:\"" + query+"\"~0"); //my conditions
QueryResponse response;
try {
if (query.length() > 1) {
response = solr.query(parameters);
SolrDocumentList dl = response.getResults();
for (int i = 0; i < dl.size(); i++) {
Synonym s = new Synonym();
s.setSynonym_id((int) dl.get(i).getFieldValue("id"));
s.setSynonymName(dl.get(i).getFieldValue("synonym")
.toString());
filteredSynonyms.add(s);
}
}
} catch (SolrServerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return filteredSynonyms;
}
I'm trying to emulate the accepted answer in this SO question: Delete all Duplicate Rows except for One in MySQL? [duplicate] with a twist, I want the data (auto-incrementing ID's) of one table to determine which rows to delete in another table. SQLFiddle here showing data.
In the fiddle referenced above, the end result I'm looking for is the rows in eventdetails_new with Event_ID = 4 & 6 to be deleted (EVENTDETAILS_ID's 5 & 6, and 9 & 10), leaving rows 3 & 5 (EVENTDETAILS_ID's 3 & 4 and 7 & 8). I hope that made sense. Ideally the rows in events_new with those same Event_ID's would get deleted as well (which I haven't started working on yet, so no code samples).
This is the query I'm trying to make work, but I'm a bit over my head:
SELECT *
FROM eventdetails_new AS EDN1, eventdetails_new AS EDN2
INNER JOIN events_new AS E1 ON `E1`.`Event_ID` = `EDN1`.`Event_ID`
INNER JOIN events_new AS E2 ON `E2`.`Event_ID` = `EDN2`.`Event_ID`
WHERE `E1`.`Event_ID` > `E2`.`Event_ID`
AND `E1`.`DateTime` = `E2`.`DateTime`
AND events_new.EventType_ID = 6;
Here's the same SQLFiddle with the results of this query. Not good. I can see the Event_ID in the data, but the query cannot for some reason. Not sure how to proceed to fix this.
I know it's a SELECT query, but I couldn't figure out a way to have two aliased tables in the DELETE query (which I think I need?). I figured if I could get a selection, I could delete it with some C# code. However ideally it could all be done in a single query or set of statements without having to go outside of MySQL.
Here's my first cut at the query, but it's just as bad:
DELETE e1 FROM eventdetails_new e1
WHERE `events_new`.`Event_ID` > `events_new`.`Event_ID`
AND events_new.DateTime = events_new.DateTime AND events_new.EventType_ID = 6;
SQLFiddle won't let me run this query at all, so it's not much help. However, it give me the same error as the one above: Error Code: 1054. Unknown column 'events_new.Event_ID' in 'where clause'
I'm by no means married to either of these queries if there's a better way. The end result I'm looking for is deleting a bunch of duplicate data.
I have hundreds of thousands of these results, and I know that roughly 1/3 of them are duplicates that I need to get rid of before we go live with the database.
Here's what I eventually ended up doing. My co-worker & I came up with a query that would give us a list of Event_ID's that had duplicate data (we actually used Access 2010's query builder and MySQL-ified it). Bear in mind this is a complete solution where the original question didn't have as much detail as far as linked tables. If you've got questions about this, feel free to ask & I'll try to help:
SELECT `Events_new`.`Event_ID`
FROM Events_new
GROUP BY `Events_new`.`PCBID`, `Events_new`.`EventType_ID`, `Events_new`.`DateTime`, `Events_new`.`User`
HAVING (((COUNT(`Events_new`.`PCBID`)) > 1) AND ((COUNT(`Events_new`.`User`)) > 1) AND ((COUNT(`Events_new`.`DateTime`)) > 1))
From this I processed each Event_ID to remove the duplicates in an iterative manner. Basically I had to delete all the child rows starting from the last lowest table so that I didn't run afoul of foreign key restraints.
This chunk of code was written in LinqPAD as C# statements: (sbCommonFunctions is an inhouse DLL designed to make most (but not all as you'll see) database functions be handled the same way or easier)
sbCommonFunctions.Database testDB = new sbCommonFunctions.Database();
testDB.Connect("production", "database", "user", "password");
List<string> listEventIDs = new List<string>();
List<string> listEventDetailIDs = new List<string>();
List<string> listTestInformationIDs = new List<string>();
List<string> listTestStepIDs = new List<string>();
List<string> listMeasurementIDs = new List<string>();
string dtQuery = (String.Format(#"SELECT `Events_new`.`Event_ID`
FROM Events_new
GROUP BY `Events_new`.`PCBID`,
`Events_new`.`EventType_ID`,
`Events_new`.`DateTime`,
`Events_new`.`User`
HAVING (((COUNT(`Events_new`.`PCBID`)) > 1)
AND ((COUNT(`Events_new`.`User`)) > 1)
AND ((COUNT(`Events_new`.`DateTime`)) > 1))"));
int iterations = 0;
DataTable dtEventIDs = getDT(dtQuery, testDB);
while (dtEventIDs.Rows.Count > 0)
{
Console.WriteLine(dtEventIDs.Rows.Count);
Console.WriteLine(iterations);
iterations++;
foreach(DataRowView eventID in dtEventIDs.DefaultView)
{
listEventIDs.Add(eventID.Row[0].ToString());
DataTable dtEventDetails = testDB.QueryDatabase(String.Format(
"SELECT * FROM EventDetails_new WHERE Event_ID = {0}",
eventID.Row[0]));
foreach(DataRowView drvEventDetail in dtEventDetails.DefaultView)
{
listEventDetailIDs.Add(drvEventDetail.Row[0].ToString());
}
DataTable dtTestInformation = testDB.QueryDatabase(String.Format(
#"SELECT TestInformation_ID
FROM TestInformation_new
WHERE Event_ID = {0}",
eventID.Row[0]));
foreach(DataRowView drvTest in dtTestInformation.DefaultView)
{
listTestInformationIDs.Add(drvTest.Row[0].ToString());
DataTable dtTestSteps = testDB.QueryDatabase(String.Format(
#"SELECT TestSteps_ID
FROM TestSteps_new
WHERE TestInformation_TestInformation_ID = {0}",
drvTest.Row[0]));
foreach(DataRowView drvTestStep in dtTestSteps.DefaultView)
{
listTestStepIDs.Add(drvTestStep.Row[0].ToString());
DataTable dtMeasurements = testDB.QueryDatabase(String.Format(
#"SELECT Measurements_ID
FROM Measurements_new
WHERE TestSteps_TestSteps_ID = {0}",
drvTestStep.Row[0]));
foreach(DataRowView drvMeasurements in dtMeasurements.DefaultView)
{
listMeasurementIDs.Add(drvMeasurements.Row[0].ToString());
}
}
}
}
testDB.Disconnect();
string mysqlConnection =
"server=server;\ndatabase=database;\npassword=password;\nUser ID=user;";
MySqlConnection connection = new MySqlConnection(mysqlConnection);
connection.Open();
//start unwinding the duplicates from the lowest level upward
whackDuplicates(listMeasurementIDs, "measurements_new", "Measurements_ID", connection);
whackDuplicates(listTestStepIDs, "teststeps_new", "TestSteps_ID", connection);
whackDuplicates(listTestInformationIDs, "testinformation_new", "testInformation_ID", connection);
whackDuplicates(listEventDetailIDs, "eventdetails_new", "eventdetails_ID", connection);
whackDuplicates(listEventIDs, "events_new", "event_ID", connection);
connection.Close();
//update iterator from inside the clause in case there are more duplicates.
dtEventIDs = getDT(dtQuery, testDB); }
}//goofy curly brace to allow LinqPAD to deal with inline classes
public void whackDuplicates(List<string> listOfIDs,
string table,
string pkID,
MySqlConnection connection)
{
foreach(string ID in listOfIDs)
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = String.Format(
"DELETE FROM " + table + " WHERE " + pkID + " = {0}", ID);
command.ExecuteNonQuery();
}
}
public DataTable getDT(string query, sbCommonFunctions.Database db)
{
return db.QueryDatabase(query);
//}/*this is deliberate, LinqPAD has a weird way of dealing with inline
classes and the last one can't have a closing curly brace (and the
first one has to have an extra opening curly brace above it, go figure)
*/
Basically this is a giant while loop, and the clause iterator is updated from inside the clause until the number of Event_ID's drops to zero (it takes 5 iterations, some of the data has as many as six duplicates).
hello guys i am try to validate username from the database with the username that the user entered in the html from, assume
un//be the variable where username entered now from html form is stored
now how to retrieve all the columns of the uname from user table
uname //column name in mysql for usernames
user //table name in mysql
and check weather the username i.e,un entered now is present or not in the database
i am using
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mebps","root","admin");
Statement stmt = (Statement) con.createStatement();
ResultSet rs = stmt.executeQuery("select un from userinfo");
while(rs.next())
{
if(rs.getString("uname") == un)
{
out.println("user is present");
}
}
There are at least two major mistakes:
You're comparing string instances by == instead of comparing their values by equals() method. The proper line would be if (rs.getString("uname").equals(un)).
You're not letting the DB do the job of returning the right row, instead you're copying the entire DB table into Java's memory and doing the comparison in Java. This is very inefficient. Make use of SQL powers the smart way so that it always returns exactly the information you need. There's for example a WHERE clause.
On an unrelated note, you seem not to be closing DB resources properly after use. This will result in resource leaking which is also a bad idea as it may cause your application to crash on long term. Further, the column name uname and un are not the same. But I'll assume it to be careless oversimplifying of the example.
Here's a minor rewrite:
public boolean exist(String username) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean exist = false;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT uname FROM userinfo WHERE uname=?");
statement.setString(1, username);
resultSet = statement.executeQuery();
exist = resultSet.next();
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return exist;
}
You see, if there's a match, then it returns true (at least one record), otherwise false (no one record). No need to copy the entire table into Java's memory and crawl through it in Java.
Last but not least, this code doesn't belong in a JSP file, but in a normal Java class, starting with a servlet. See also our servlets wiki page to learn more about it.
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.