Compiling...
src\server\model\players\packets\Commands.java:1389: reached end of file while parsing
}→
^
1 error
Press any key to continue . . .
What am I missing?
if (playerCommand.startsWith("auth") && playerCommand.length() > 5) {
if (!Config.MYSQL_ACTIVE) {
c.sendMessage("Sorry this is currently disabled.");
return;
} else {
try {
PreparedStatement ps = Database.getConnection().prepareStatement("SELECT * FROM votes WHERE username = ? AND used = '1' LIMIT 1");
ps.setString(1, c.playerName);
ResultSet results = ps.executeQuery();
if (results.next()) {
c.sendMessage("You have already voted once today.");
} else {
ps.close();
ps = Database.getConnection().prepareStatement("SELECT * FROM votes WHERE authcode = ? AND used = '0' LIMIT 1");
ps.setString(1, playerCommand.substring(5));
results = ps.executeQuery();
if (results.next()) {
ps.close();
ps = Database.getConnection().prepareStatement("UPDATE votes SET used = '1' WHERE authcode = ?");
ps.setString(1, playerCommand.substring(5));
ps.executeUpdate();
c.getItems().addItem(995, 10000000);
c.sendMessage("Thank you for voting.");
} else {
c.sendMessage("The auth code is not valid!");
}
}
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return;
Make sure that your class have proper opening and closing braces { ... }
A missing brace is typically what causes such an error...
Related
I'm trying to take two random rowid from my database. Everything works but I have a scenario when there is only one rowid. I want to make a loop on my try/catch until there is second number in my database.
What I'm doing wrong? Thank you
public void Kaslaimejo() {
String sql = "SELECT rowid FROM Zaidejai WHERE Pirmas < 4 ORDER BY random() LIMIT 2";
Integer value1 = null, value2 = null;
Integer judesiukas1 = null, judesiukas2 = null;
int a = 0;
int k = 15; // kiek kartu? Reikia infinity padaryti
for (a = 0; a < 3; a++) {
try {
Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
value1 = rs.getInt("rowid");
if (rs.next()) {
value2 = rs.getInt("rowid");
PreparedStatement buvo = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo.setInt(1, i);
buvo.setInt(2, value1);
int buvolala = buvo.executeUpdate ();
PreparedStatement buvo2 = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo2.setInt(1, i);
buvo2.setInt(2, value2);
int buvolala2 = buvo2.executeUpdate ();//
i++;
}
System.out.println("Pirmas zaidejas" + value1); // atspausdina 1 random zaideja is duomenu bazes
System.out.println("Antras zaidejas" + value2); // atspausdina 2 random zaideja is duomenu bazes
}
} catch (SQLException e) {
a--;
//System.out.println(e.getMessage());
}
}
}
Right now my program loops two times and then gives me SQLException. How I can loop my program until there is no SQLException?
OK, I've tried to write what I think you're trying to do.
You wait for ever until someone puts at least two entries in the database.
You extract two values, process them, then wait some more.
Some points to watch out:
1. Object comparisons need to be made with .equals() not with ==
2. You might want to provide some way to break out of the infinite loop I've written (while(true)).
3. Careful with null values. They might produce NullPointerException.
4. Try to break up your code into methods. Each large block of code could go into each own method.
public void Kaslaimejo(){
String sql = "SELECT rowid FROM Zaidejai WHERE Pirmas < 4 ORDER BY random() LIMIT 2";
Integer judesiukas1 = null, judesiukas2 = null;
while(true) {
List<Integer> values = new ArrayList<>();
while (values.size() < 2) {
try (Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
if( rs.next() ){
Integer value = rs.getInt("rowid");
values.add(value);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
try( Connection conn = Serveris.connect()) {
PreparedStatement buvo = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo.setInt(1, i);
buvo.setInt(2, values.get(0));
int buvolala = buvo.executeUpdate ();
PreparedStatement buvo2 = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo2.setInt(1, i);
buvo2.setInt(2, values.get(1));
int buvolala2 = buvo2.executeUpdate ();//
i++;
}catch (SQLException e) {
e.printStackTrace();
}
Connection conn = Serveris.connect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT Pirmas FROM Zaidejai WHERE rowid = ?");
PreparedStatement pstmt2 = conn.prepareStatement("SELECT Pirmas FROM Zaidejai WHERE rowid = ?");
pstmt.setInt(1, values.get(0));
pstmt2.setInt(1, values.get(1));
ResultSet myrsv = pstmt.executeQuery();
ResultSet myrsv2 = pstmt2.executeQuery();
{
if (myrsv.next()) {
judesiukas1 = myrsv.getInt("Pirmas");
if (myrsv2.next()) {
judesiukas2 = myrsv2.getInt("Pirmas");
}
}
//System.out.println("Pirmo zaidejo veiksmas" + myrsv.getInt("Pirmas"));
//System.out.println("Antro zaidejo veiksmas" + myrsv2.getInt("Pirmas"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (judesiukas1.equals(judesiukas2)) // careful here. NullPointerException may happen.
{
try {
PreparedStatement laim = conn.prepareStatement("UPDATE Zaidejai SET Rezultatas = ? WHERE rowid = ?"); // ble ble update reikia naudoti , o ne insert into. Insert kai sukuriame nauja kazka tik
PreparedStatement laim2 = conn.prepareStatement("UPDATE Zaidejai SET Rezultatas = ? WHERE rowid = ?");
laim.setString(1, "Lygiosios");
laim.setInt(2, values.get(0));
laim2.setString(1, "Lygiosios");
laim2.setInt(2, values.get(1));
int irasyk = laim.executeUpdate (); // kodel executeupdate, o ne executequery????
int irasyk2 = laim2.executeUpdate (); // kodel executeupdate, o ne executequery????
{
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("Lygiosios");
} else {
// (1) - Rock
// (2) Scissors
// (3) - Paper
switch (values.get(0)){
case 1:
if (judesiukas2 == 2)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
case 2:
if (judesiukas2 == 3)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
case 3:
if (judesiukas2 == 1)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
}
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The logic becomes easier if you add the values to a list
var values = new ArrayList<Integer>();
while (values.Count < 2) {
try (Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql))
{
while (values.Count < 2 && rs.next()) {
Integer v = rs.getInt("rowid");
values.Add(v);
}
} catch (SQLException e) {
}
}
//TODO: process the values here
The advantage is, that you can retrieve one value at the first database query and the second at a later one or both in the same round and you don't have to keep track of which one of two variables to use.
(Bear with me with the syntax details, I'm not a Java programmer.)
How i can loop my program until there is no SQLException?
Change this (because, it will only allow to loop two times)
for (a = 0; a < 2; a++) {
to
while(true)
Put everything inside while(true), if exception occurred, then it will come out from the while loop. Something similar :
try
{
while(true)
{
...
...
}
...
}
catch(SQLException e)
{
// do somthing
}
I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html
This question already has answers here:
Passing table name as parameter of prepared statement [duplicate]
(3 answers)
Closed 6 years ago.
public List<User> arrangeUsers(String option) {
String query = "";
if (option.equals("lastNameAsc")) {
query = "SELECT * FROM ? ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query = "SELECT * FROM ? ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
if (searchList.size() > 0) {
stmt.setString(1, "search_results");
searchList.clear();
listChoice = true;
} else {
stmt.setString(1, "users");
users.clear();
listChoice = false;
}
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
The above method returns an error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''users' ORDER BY lastName DESC' at line 1 " error.
The method is supposed to arrange a list of users (a table) according to the order required by the client. Any suggestions what is the reason for the error message? I am ready to provide any additional details if necessary.
A table name can't be used as a parameter. It must be hardcoded. You can do something like:
public List<User> arrangeUsers(String option) {
String query = "SELECT * FROM ";
if (searchList.size() > 0) {
query += "search_results ";
searchList.clear();
listChoice = true;
} else {
query += "users ";
users.clear();
listChoice = false;
}
if (option.equals("lastNameAsc")) {
query += "ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query += "ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query += "ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query += "ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
Hope it helps.
I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}
The password and username are retrieved from the database. If one row is returned, a user exists. However, the below code says that the user does not exist even if the username and password are correct.
if(con != null) {
try {
String query = "select * from users where username = '"+user.getText()+"' and password = '"+pasword.getText()+"'";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
int count = 0;
while(rs.next()) {
count = count + 1;
}
if(count == 1) {
JOptionPane.showMessageDialog(null, "user exist");
} else {
JOptionPane.showMessageDialog(null, "user doesnot exist");
}
rs.close();
ps.close();
} catch (Exception e1) {
}
}
It´s a sensible code, but you should to write the
e.printStackTrace()
in the catch block, maybe an exception it's occurs. Check the user.getText() and password.getText() content, also you can apply an user.getText().trim() for example, to delete de blank spaces. Then try this:
while(rs.next()) {
count++;
}
if(count > 0) {
JOptionPane.showMessageDialog(null, "user exist");
} else {
JOptionPane.showMessageDialog(null, "user doesnot exist");
}
Good luck!