Java methods to add and authenticate users in MySQLphp one-time prepared statement execution functionThoughts on organizing code for multiple mysql queries in php scriptsAvoid duplicate conditional checks in multiple boolean conditionsMySQL Java in JTableCode Golf challenge that plays MafiaQuerying Facebook for details of a user's OAuth tokenImplementation of stackJava MySQL handler for a Minecraft modJava JDBC: MySQL database-wrapperAuthenticate users in Django
What is the opposite of "hunger level"?
Is Fourier series a sampled version of Fourier transform?
Select elements of a list by comparing it to another list
When did Bilbo and Frodo learn that Gandalf was a Maia?
What are the advantages of this gold finger shape?
What are some tips and tricks for finding the cheapest flight when luggage and other fees are not revealed until far into the booking process?
How does the Moon's gravity affect Earth's oceans despite Earth's stronger gravitational pull?
Has there ever been a truly bilingual country prior to the contemporary period?
Knights and Knaves on a (Not So) Deserted Island
Physical Interpretation of an Overdamped Pendulum
Quick destruction of a helium filled airship?
What is the purpose/function of this power inductor in parallel?
What was the intention with the Commodore 128?
Why is the battery jumpered to a resistor in this schematic?
How do I pass a "list of lists" as the argument to a function of the form F[x,y]?
Does writing regular diary entries count as writing practice?
Why should I pay for an SSL certificate?
global variant of csname…endcsname
What's the relationship betweeen MS-DOS and XENIX?
Can anybody tell me who this Pokemon is?
Output with the same length always
Do I need to start off my book by describing the character's "normal world"?
Have there ever been other TV shows or Films that told a similiar story to the new 90210 show?
What's the point of writing that I know will never be used or read?
Java methods to add and authenticate users in MySQL
php one-time prepared statement execution functionThoughts on organizing code for multiple mysql queries in php scriptsAvoid duplicate conditional checks in multiple boolean conditionsMySQL Java in JTableCode Golf challenge that plays MafiaQuerying Facebook for details of a user's OAuth tokenImplementation of stackJava MySQL handler for a Minecraft modJava JDBC: MySQL database-wrapperAuthenticate users in Django
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
I'm going through some code and trying to figure out how to get rid of duplicates from the following two methods. Both methods execute a simple login/register query to a local MySQL DB. I couldnt figure out a good design pattern to solve my problem, especially to get rid of the duplicate try-catch.
Any advice?
public class DatabaseHandler
[...]
public static boolean checkLogin(String username, String password)
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "select * from users where username = ? and password = ? ";
try
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
return result.next(); //True if User exists
catch(SQLException e)
return false;
finally
try
statement.close();
catch (SQLException e)
e.printStackTrace();
public static boolean registerUser(String username, String password)
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "insert into users (username, password) values (?, ?)";
try
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
statement.executeUpdate();
return true;
catch(SQLException e)
return false;
finally
try
statement.close();
catch (SQLException e)
e.printStackTrace();
```
java mysql authentication jdbc
New contributor
Clayy91 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
I'm going through some code and trying to figure out how to get rid of duplicates from the following two methods. Both methods execute a simple login/register query to a local MySQL DB. I couldnt figure out a good design pattern to solve my problem, especially to get rid of the duplicate try-catch.
Any advice?
public class DatabaseHandler
[...]
public static boolean checkLogin(String username, String password)
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "select * from users where username = ? and password = ? ";
try
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
return result.next(); //True if User exists
catch(SQLException e)
return false;
finally
try
statement.close();
catch (SQLException e)
e.printStackTrace();
public static boolean registerUser(String username, String password)
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "insert into users (username, password) values (?, ?)";
try
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
statement.executeUpdate();
return true;
catch(SQLException e)
return false;
finally
try
statement.close();
catch (SQLException e)
e.printStackTrace();
```
java mysql authentication jdbc
New contributor
Clayy91 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
I'm going through some code and trying to figure out how to get rid of duplicates from the following two methods. Both methods execute a simple login/register query to a local MySQL DB. I couldnt figure out a good design pattern to solve my problem, especially to get rid of the duplicate try-catch.
Any advice?
public class DatabaseHandler
[...]
public static boolean checkLogin(String username, String password)
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "select * from users where username = ? and password = ? ";
try
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
return result.next(); //True if User exists
catch(SQLException e)
return false;
finally
try
statement.close();
catch (SQLException e)
e.printStackTrace();
public static boolean registerUser(String username, String password)
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "insert into users (username, password) values (?, ?)";
try
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
statement.executeUpdate();
return true;
catch(SQLException e)
return false;
finally
try
statement.close();
catch (SQLException e)
e.printStackTrace();
```
java mysql authentication jdbc
New contributor
Clayy91 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
I'm going through some code and trying to figure out how to get rid of duplicates from the following two methods. Both methods execute a simple login/register query to a local MySQL DB. I couldnt figure out a good design pattern to solve my problem, especially to get rid of the duplicate try-catch.
Any advice?
public class DatabaseHandler
[...]
public static boolean checkLogin(String username, String password)
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "select * from users where username = ? and password = ? ";
try
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
return result.next(); //True if User exists
catch(SQLException e)
return false;
finally
try
statement.close();
catch (SQLException e)
e.printStackTrace();
public static boolean registerUser(String username, String password)
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "insert into users (username, password) values (?, ?)";
try
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
statement.executeUpdate();
return true;
catch(SQLException e)
return false;
finally
try
statement.close();
catch (SQLException e)
e.printStackTrace();
```
java mysql authentication jdbc
java mysql authentication jdbc
New contributor
Clayy91 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Clayy91 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 6 hours ago


200_success
135k21 gold badges173 silver badges443 bronze badges
135k21 gold badges173 silver badges443 bronze badges
New contributor
Clayy91 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 8 hours ago
Clayy91Clayy91
212 bronze badges
212 bronze badges
New contributor
Clayy91 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Clayy91 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
Funny coincidence, I just created the solution for your problem (but in PHP). The common thing here is the one-time use of a prepared statement, the difference is in the query string and arguments, so what you need is a function that accepts a query string, an argument determining what execution function to use (executeQuery()
or executeUpdate()
) and the parameters for the query:
// note: QueryType is an enum you should define
public static ResultSet query(String sql, QueryType queryType, Object... queryArgs)
// ...
Include the try-catch
blocks in this function too of course, and return null
when according to queryType
there should be no results.
Note: I have no experience with database interaction with Java, so if there are only 2 different statement execution functions then you can use a boolean argument instead of the enum QueryType
.
Then your code could look like this:
public static boolean checkLogin(String username, String password)
String sql = "select * from users where username = ? and password = ? ";
ResultSet result = query(sql, QueryType.RETURN_RESULT, username, password);
return result.next(); // true if User exists
A note about your query string: I find it more convenient to use CAPS for keywords and lowercase text for names, it highlights the structure of the query.
$endgroup$
$begingroup$
thanks for your answer! Few things ive noticed when i tried to implement your solution: TheexecuteUpdate()
Method returns an Integer, so i cant haveResultSet
as return type. I could however, useexecuteQuery()
for all SQL-querys. Problem is, i would have to catch aSQLException
in thecheckLogin
Method, becauseresult.next()
throws such. Kind of destroys the intend of thequery
Method. I thought about some kind of Interface/Abstract Class Pattern in the first place to solve this problem, but cant figure out. I will continue playing around with your suggestion tho!
$endgroup$
– Clayy91
6 hours ago
$begingroup$
@Clayy91 You could implement aQueryResult
class with aresultType
property that based on it you'll know what other property of that class contains the result (int resultInt
orResultSet resultSet
for example) - or look straight at the property you expect to contain the result according to the type of query you made.
$endgroup$
– potato
4 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Clayy91 is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226281%2fjava-methods-to-add-and-authenticate-users-in-mysql%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Funny coincidence, I just created the solution for your problem (but in PHP). The common thing here is the one-time use of a prepared statement, the difference is in the query string and arguments, so what you need is a function that accepts a query string, an argument determining what execution function to use (executeQuery()
or executeUpdate()
) and the parameters for the query:
// note: QueryType is an enum you should define
public static ResultSet query(String sql, QueryType queryType, Object... queryArgs)
// ...
Include the try-catch
blocks in this function too of course, and return null
when according to queryType
there should be no results.
Note: I have no experience with database interaction with Java, so if there are only 2 different statement execution functions then you can use a boolean argument instead of the enum QueryType
.
Then your code could look like this:
public static boolean checkLogin(String username, String password)
String sql = "select * from users where username = ? and password = ? ";
ResultSet result = query(sql, QueryType.RETURN_RESULT, username, password);
return result.next(); // true if User exists
A note about your query string: I find it more convenient to use CAPS for keywords and lowercase text for names, it highlights the structure of the query.
$endgroup$
$begingroup$
thanks for your answer! Few things ive noticed when i tried to implement your solution: TheexecuteUpdate()
Method returns an Integer, so i cant haveResultSet
as return type. I could however, useexecuteQuery()
for all SQL-querys. Problem is, i would have to catch aSQLException
in thecheckLogin
Method, becauseresult.next()
throws such. Kind of destroys the intend of thequery
Method. I thought about some kind of Interface/Abstract Class Pattern in the first place to solve this problem, but cant figure out. I will continue playing around with your suggestion tho!
$endgroup$
– Clayy91
6 hours ago
$begingroup$
@Clayy91 You could implement aQueryResult
class with aresultType
property that based on it you'll know what other property of that class contains the result (int resultInt
orResultSet resultSet
for example) - or look straight at the property you expect to contain the result according to the type of query you made.
$endgroup$
– potato
4 hours ago
add a comment |
$begingroup$
Funny coincidence, I just created the solution for your problem (but in PHP). The common thing here is the one-time use of a prepared statement, the difference is in the query string and arguments, so what you need is a function that accepts a query string, an argument determining what execution function to use (executeQuery()
or executeUpdate()
) and the parameters for the query:
// note: QueryType is an enum you should define
public static ResultSet query(String sql, QueryType queryType, Object... queryArgs)
// ...
Include the try-catch
blocks in this function too of course, and return null
when according to queryType
there should be no results.
Note: I have no experience with database interaction with Java, so if there are only 2 different statement execution functions then you can use a boolean argument instead of the enum QueryType
.
Then your code could look like this:
public static boolean checkLogin(String username, String password)
String sql = "select * from users where username = ? and password = ? ";
ResultSet result = query(sql, QueryType.RETURN_RESULT, username, password);
return result.next(); // true if User exists
A note about your query string: I find it more convenient to use CAPS for keywords and lowercase text for names, it highlights the structure of the query.
$endgroup$
$begingroup$
thanks for your answer! Few things ive noticed when i tried to implement your solution: TheexecuteUpdate()
Method returns an Integer, so i cant haveResultSet
as return type. I could however, useexecuteQuery()
for all SQL-querys. Problem is, i would have to catch aSQLException
in thecheckLogin
Method, becauseresult.next()
throws such. Kind of destroys the intend of thequery
Method. I thought about some kind of Interface/Abstract Class Pattern in the first place to solve this problem, but cant figure out. I will continue playing around with your suggestion tho!
$endgroup$
– Clayy91
6 hours ago
$begingroup$
@Clayy91 You could implement aQueryResult
class with aresultType
property that based on it you'll know what other property of that class contains the result (int resultInt
orResultSet resultSet
for example) - or look straight at the property you expect to contain the result according to the type of query you made.
$endgroup$
– potato
4 hours ago
add a comment |
$begingroup$
Funny coincidence, I just created the solution for your problem (but in PHP). The common thing here is the one-time use of a prepared statement, the difference is in the query string and arguments, so what you need is a function that accepts a query string, an argument determining what execution function to use (executeQuery()
or executeUpdate()
) and the parameters for the query:
// note: QueryType is an enum you should define
public static ResultSet query(String sql, QueryType queryType, Object... queryArgs)
// ...
Include the try-catch
blocks in this function too of course, and return null
when according to queryType
there should be no results.
Note: I have no experience with database interaction with Java, so if there are only 2 different statement execution functions then you can use a boolean argument instead of the enum QueryType
.
Then your code could look like this:
public static boolean checkLogin(String username, String password)
String sql = "select * from users where username = ? and password = ? ";
ResultSet result = query(sql, QueryType.RETURN_RESULT, username, password);
return result.next(); // true if User exists
A note about your query string: I find it more convenient to use CAPS for keywords and lowercase text for names, it highlights the structure of the query.
$endgroup$
Funny coincidence, I just created the solution for your problem (but in PHP). The common thing here is the one-time use of a prepared statement, the difference is in the query string and arguments, so what you need is a function that accepts a query string, an argument determining what execution function to use (executeQuery()
or executeUpdate()
) and the parameters for the query:
// note: QueryType is an enum you should define
public static ResultSet query(String sql, QueryType queryType, Object... queryArgs)
// ...
Include the try-catch
blocks in this function too of course, and return null
when according to queryType
there should be no results.
Note: I have no experience with database interaction with Java, so if there are only 2 different statement execution functions then you can use a boolean argument instead of the enum QueryType
.
Then your code could look like this:
public static boolean checkLogin(String username, String password)
String sql = "select * from users where username = ? and password = ? ";
ResultSet result = query(sql, QueryType.RETURN_RESULT, username, password);
return result.next(); // true if User exists
A note about your query string: I find it more convenient to use CAPS for keywords and lowercase text for names, it highlights the structure of the query.
edited 4 hours ago
answered 7 hours ago
potatopotato
49812 bronze badges
49812 bronze badges
$begingroup$
thanks for your answer! Few things ive noticed when i tried to implement your solution: TheexecuteUpdate()
Method returns an Integer, so i cant haveResultSet
as return type. I could however, useexecuteQuery()
for all SQL-querys. Problem is, i would have to catch aSQLException
in thecheckLogin
Method, becauseresult.next()
throws such. Kind of destroys the intend of thequery
Method. I thought about some kind of Interface/Abstract Class Pattern in the first place to solve this problem, but cant figure out. I will continue playing around with your suggestion tho!
$endgroup$
– Clayy91
6 hours ago
$begingroup$
@Clayy91 You could implement aQueryResult
class with aresultType
property that based on it you'll know what other property of that class contains the result (int resultInt
orResultSet resultSet
for example) - or look straight at the property you expect to contain the result according to the type of query you made.
$endgroup$
– potato
4 hours ago
add a comment |
$begingroup$
thanks for your answer! Few things ive noticed when i tried to implement your solution: TheexecuteUpdate()
Method returns an Integer, so i cant haveResultSet
as return type. I could however, useexecuteQuery()
for all SQL-querys. Problem is, i would have to catch aSQLException
in thecheckLogin
Method, becauseresult.next()
throws such. Kind of destroys the intend of thequery
Method. I thought about some kind of Interface/Abstract Class Pattern in the first place to solve this problem, but cant figure out. I will continue playing around with your suggestion tho!
$endgroup$
– Clayy91
6 hours ago
$begingroup$
@Clayy91 You could implement aQueryResult
class with aresultType
property that based on it you'll know what other property of that class contains the result (int resultInt
orResultSet resultSet
for example) - or look straight at the property you expect to contain the result according to the type of query you made.
$endgroup$
– potato
4 hours ago
$begingroup$
thanks for your answer! Few things ive noticed when i tried to implement your solution: The
executeUpdate()
Method returns an Integer, so i cant have ResultSet
as return type. I could however, use executeQuery()
for all SQL-querys. Problem is, i would have to catch a SQLException
in the checkLogin
Method, because result.next()
throws such. Kind of destroys the intend of the query
Method. I thought about some kind of Interface/Abstract Class Pattern in the first place to solve this problem, but cant figure out. I will continue playing around with your suggestion tho!$endgroup$
– Clayy91
6 hours ago
$begingroup$
thanks for your answer! Few things ive noticed when i tried to implement your solution: The
executeUpdate()
Method returns an Integer, so i cant have ResultSet
as return type. I could however, use executeQuery()
for all SQL-querys. Problem is, i would have to catch a SQLException
in the checkLogin
Method, because result.next()
throws such. Kind of destroys the intend of the query
Method. I thought about some kind of Interface/Abstract Class Pattern in the first place to solve this problem, but cant figure out. I will continue playing around with your suggestion tho!$endgroup$
– Clayy91
6 hours ago
$begingroup$
@Clayy91 You could implement a
QueryResult
class with a resultType
property that based on it you'll know what other property of that class contains the result (int resultInt
or ResultSet resultSet
for example) - or look straight at the property you expect to contain the result according to the type of query you made.$endgroup$
– potato
4 hours ago
$begingroup$
@Clayy91 You could implement a
QueryResult
class with a resultType
property that based on it you'll know what other property of that class contains the result (int resultInt
or ResultSet resultSet
for example) - or look straight at the property you expect to contain the result according to the type of query you made.$endgroup$
– potato
4 hours ago
add a comment |
Clayy91 is a new contributor. Be nice, and check out our Code of Conduct.
Clayy91 is a new contributor. Be nice, and check out our Code of Conduct.
Clayy91 is a new contributor. Be nice, and check out our Code of Conduct.
Clayy91 is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226281%2fjava-methods-to-add-and-authenticate-users-in-mysql%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown