indexof string matching from data base and runtime text - java

I want to make website blocker in my web browser, so I made a database which contain the names of website. Now I want to check the string from database with indexOf method, but it is giving me an error while I am trying to check. Please tell me where my mistake is. Rest of the code is correct and working only database part is not working.
public void loadURL(final String url) {
try {
Connection myconnection;
myconnection = DriverManager.getConnection("jdbc:mysql://localhost/bookmarks", "roo t", "");
try {
String q = "select * from block where url=?";
PreparedStatement mysat = myconnection.prepareStatement(q);
ResultSet myresult = mysat.executeQuery();
int index1;
while (myresult.next()) {
String s2 = myresult.setString("url");
String s1 = txtURL.getText();
index1 = s1.indexOf(s2);
}
if (index1 == -1) {
JOptionPane.showMessageDialog(rootPane, "You Cannot access this website", "Error", JOptionPane.ERROR_MESSAGE);
} else {
Platform.runLater(new Runnable() {
#Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
myconnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

if you use PreparedStatement you have to set a
value for each ? marker:
String q="select * from block where url=?";
PreparedStatement mysat=myconnection.prepareStatement(q);
mysat.setString(1,"www.google.com");
without you have an invalid sql syntax.

Related

Data i've inserted into table does not replace old data, is there a way to replace data if it's already there?

Problem is the following: I am saving hashed password for a school project, however i am stuck on the syntax for the SQL statement to replace the data if it is already present. The table will only need to store a single username/password combination.
public class DatabaseManager {
String dbPath = "jdbc:sqlite:test.db";
public DatabaseManager () {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection(dbPath);
if (conn != null) {
System.out.println("Connected to the database");
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
// Setting up database
databaseSetup(conn);
boolean tempInsertion = databaseInsert("pancake", "house", conn);
// Inserting data
if (tempInsertion) {
System.out.println("Data insertion failed");
}
// Retrieving data
List<String> retrievedData = databaseSelect(conn);
if (retrievedData == null) {
System.out.println("Data extraction failed");
}
else {
System.out.println(retrievedData.size());
}
conn.close();
}
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private boolean databaseInsert(String username, String password, Connection conn) {
String sqlInsert = "INSERT OR REPLACE INTO login(username, password) VALUES(?,?)";
PreparedStatement prepStatement;
try {
prepStatement = conn.prepareStatement(sqlInsert);
prepStatement.setString(1, encrypt(username));
prepStatement.setString(2, encrypt(password));
prepStatement.executeUpdate();
} catch (SQLException e) {
return false;
}
return true;
}
private List<String> databaseSelect(Connection conn) {
List<String> tempList = new ArrayList<String>();
String sqlSelect = "SELECT * FROM login";
Statement stmt;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlSelect);
tempList.add(rs.getString("username"));
tempList.add(rs.getString("password"));
int columnsNumber = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rs.getMetaData().getColumnName(i));
}
System.out.println("");
}
} catch (SQLException e) {
return null;
}
return tempList;
}
private void databaseSetup( Connection conn) {
String sqlExpression = "CREATE TABLE login (username varchar(255), password varchar(255))";
try {
Statement statement = conn.createStatement();
statement.execute(sqlExpression);
} catch (SQLException e) {}
}
private String encrypt(String string) {
try {
MessageDigest exampleCrypt = MessageDigest.getInstance("SHA1");
exampleCrypt.reset();
exampleCrypt.update(string.getBytes("UTF-8"));
return convertByte(exampleCrypt.digest());
}
catch(NoSuchAlgorithmException e) {
System.out.println("Error, cannot encrypt string");
e.printStackTrace();
}
catch(UnsupportedEncodingException e) {
System.out.println("Error, cannot encrypt string");
e.printStackTrace();
}
return null;
}
private static String convertByte(final byte[] hash) {
Formatter formatter1 = new Formatter();
for (byte i : hash) {
formatter1.format("%02x", i);
}
String encryptedData = formatter1.toString();
formatter1.close();
return encryptedData;
}
}
The problem as stated, is that i'd like to only store a single password/username combination at a time, as a hash. However, when this happens it duplicates the hash combination, instead of replacing it.

Using JRadioButtons with a derby database

I am trying to use the user's selection of a JRadioButton as part of a SELECT query for a derby database. For some reason, when I click the search button (called diffSearchbtn), nothing happens. What should be happening is that the SELECT query puts all the entries that match the criteria of the radio button into a JTable on a panel called dispPanel.
Here is the code for the method that assigns a string based on what button the user clicks.
private String tagValid()
{
String diff = "";
if (dEasybtn.isSelected())
{
diff = "EASY";
System.out.println("easy");
}
else if (dMedbtn.isSelected())
{
diff = "MEDIUM";
System.out.println("medium");
}
else if (dHardbtn.isSelected())
{
diff = "HARD";
System.out.println("hard");
}
else
{
diff = null;
}
return null;
}
Here is the code that is meant to display the form:
private void diffSearchbtnActionPerformed(java.awt.event.ActionEvent evt) {
if(tagValid()!=null)
{
String q = String.format("Select* from Gabby.PData where DIFFICULTY = '%d'", tagValid());
ResultSet res = Backend.query(q);
guiTable.setModel(DbUtils.resultSetToTableModel(res));
int counter = 3;
try
{
while (res.next()) {
counter++;
System.out.println("increasing counter");
}
}
catch (SQLException ex) {
Logger.getLogger(WikiPlantGUI.class.getName()).log(Level.SEVERE, null, ex);
}
if (counter == 0)
{
basePanel.removeAll();
basePanel.add(NoMatchPanel);
basePanel.repaint();
basePanel.revalidate();
}
else
{
basePanel.removeAll();
basePanel.add(dispPanel);
basePanel.repaint();
basePanel.revalidate();
}
}
}
Here is the code from the class Backend:
public static ResultSet query(String q)
{
try {
System.out.println("a query");
Statement stat = myConObj.createStatement();
ResultSet res = stat.executeQuery(q);
return res;
}
catch (SQLException e)
{
e.printStackTrace(); // tells what the error is
return null; // returns nothing
}
}
GUI screenshot
There are no error messages, and the program otherwise runs perfectly. Any idea on what's going wrong?

Discord bot unusually repeats

So I'm trying to create a discord bot that has simple access to a database for printing out values, my code currently will print the values to the discord server but it repeats them 5 times.
Bot functionality class:
private MySQLAccess sql = new MySQLAccess();
public static void main(String[] args) throws Exception {
JDABuilder ark = new JDABuilder(AccountType.BOT);
ark.setToken("insert_discord_token_here");
ark.addEventListener(new MessageListener());
ark.buildAsync();
}
#Override
public void onMessageReceived(MessageReceivedEvent e) {
if (e.getAuthor().isBot()) return;
Message msg = e.getMessage();
String str = msg.getContentRaw();
//Ping pong
if (str.equalsIgnoreCase("!ping")) {
e.getChannel().sendMessage("Pong!").queue();
}
//Bal check
if (str.contains("!bal")) {
String user = str.substring(5);
System.out.println(user);
try {
sql.readDataBase(e.getChannel(), user);
} catch (Exception e1) {
}
}
}
Database Access Class:
private Connection connect = null;
private Statement statement = null;
private ResultSet resultSet = null;
private final String user = "pass";
private final String pass = "user";
public void readDataBase(MessageChannel msg, String username) throws Exception {
//Retrieve data and search for username
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/serverusers?allowPublicKeyRetrieval=true&useSSL=false", user, pass);
statement = connect.createStatement();
resultSet = statement
.executeQuery("select * from serverusers.userinfo where user=\"" + username + "\"");
writeResultSet(resultSet, msg);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeResultSet(ResultSet resultSet, MessageChannel msg) throws SQLException {
// Check resultSet and print its contents
if (resultSet.next()) {
String user = resultSet.getString(2);
Double website = resultSet.getDouble(3);
msg.sendMessage("User: " + user).queue();
msg.sendMessage("Bank Amount: " + website).queue();
}
}
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
When the program is run it finds the correct data that I'm looking for and the search function is fine, but for some odd reason the program will spit the same username and balance out 5 times.
Screenshot of Discord Bot
The common mistake here is that you run the program multiple times, each instance then responds accordingly with the same thing. You can check if that is the case by opening the task manager and looking for java processes. This often occurs with developers using the Eclipse IDE because of the console hiding other processes behind a drop-down menu on the console.

Can not insert user into database in JSON Java Restful

I'm facing the problem about insert user in database. Im using Restful and JDBC to parse data to android, I have two classes to perform insert user following as:
Register.java
#Path("/register")
public class Register {
#GET
#Path("/doregister")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("name") String name, #QueryParam("username") String uname, #QueryParam("password") String pwd){
String response = "";
int retCode = registerUser(name, uname, pwd);
if(retCode == 0){
response = Utitlity.constructJSON("register",true);
}else if(retCode == 1){
response = Utitlity.constructJSON("register",false, "You are already registered");
}else if(retCode == 2){
response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
}else if(retCode == 3){
response = Utitlity.constructJSON("register",false, "Error occured");
}
return response;
}
private int registerUser(String name, String uname, String pwd){
System.out.println("Inside check registerUser method() ");
int result = 3;
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
try {
if(DBConnection.insertUser(name, uname, pwd)){
System.out.println("RegisterUSer if");
result = 0;
}
} catch(SQLException sqle){
System.out.println("RegisterUSer catch sqle");
//When Primary key violation occurs that means user is already registered
if(sqle.getErrorCode() == 1062){
result = 1;
}
else if(sqle.getErrorCode() == 1064){
System.out.println(sqle.getErrorCode());
result = 2;
}
}
catch (Exception e) {
System.out.println("Inside checkCredentials catch e ");
result = 3;
}
}else{
System.out.println("Inside checkCredentials else");
result = 3;
}
return result;
}
}
DBConnect.java
public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception {
boolean insertStatus = false;
Connection dbConn = null;
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "INSERT into ACCOUNT(name, username, password) values('"+name+ "',"+"'"
+ uname + "','" + pwd + "')";
//System.out.println(query);
int records = stmt.executeUpdate(query);
//System.out.println(records);
//When record is successfully inserted
if (records > 0) {
insertStatus = true;
}
} catch (SQLException sqle) {
//sqle.printStackTrace();
throw sqle;
} catch (Exception e) {
//e.printStackTrace();
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return insertStatus;
}
My table ACCOUNT:
When I debugged on Eclipse, I see the result return is fine, but If I use Advanced rest client tool to get data, it happened an exception:
URL Json:
http://localhost:9999/webserver/register/doregister?name=tester&username=tester#gmail.com&password=test12345
status of result response:
{
"tag": "register",
"status": false,
"error_msg": "Error occured"
}
I have found and tried a lot of ways but not found the cause
How to fix the problem and insert user into database? Thank so much !

Not Able to give previleges...Openoffice error

This is the code i had written to save the data into the openoffice database.
but its giving error.i m not understanding y it is appearing.
package coop.data;
import java.sql.*;
/**
*
* #author spk
*/
public class Connectionsetting {
private static Connection con;
private static Statement sm;
private static ResultSet rs;
public static void close()
{
try
{
sm.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void connection() {
String db_file_name_prefix = "/home/spk/Desktop/CooperHr/mydb.odb";
/*
If required change the file name if you are working in windows os
connection is in work
*/
try {
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Found");
con=DriverManager.getConnection("jdbc:hsqldb:file"+db_file_name_prefix,"sa", "");
System.out.println("Connection Eshtablished");
// con.setAutoCommit(false);
sm=con.createStatement();
// sm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int executeupdate(String query) {
//Execute & update block insert, update, delete statements
int bool = 0;
try {
bool=sm.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
public ResultSet executeQuery(String query) {
//Block Returns single resultset,,,sql statements such as sql select
ResultSet rs=null;
try {
rs = sm.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
public boolean checkTableStatus(String tblName) {
String sql = "selec * from cat";
ResultSet rs=null;
boolean status = false;
int i = 0;
String allTableNames[] = new String[20];
try {
connection();
rs = sm.executeQuery(sql);
while (rs.next()) {
allTableNames[i] = rs.getString(0);
i++;
if (allTableNames[i].equals(tblName)) {
status = true;
break;
} else {
status = false;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
public static void main(String []args)
{
String query,s1,s2,s3,s4,s5,s6,s7,s8;
Connectionsetting cn=new Connectionsetting();
cn.connection();
s1="same";
s2="sam";
s3="923847";
s4="sam";
s5="sam";
s6="sam";
s7="sam";
s8="R01";
query="insert into Agency_Master values("+s1+","+s2+","+s3+","+s4+","+s5+","+s6+","+s7+","+s8+")";
cn.executeupdate(query);
}
}
This is the error..I m getting it when i trying to save the data into the database
Can any one plz tell me where i m wrong.
Thank you.
run:
Driver Found
Connection Eshtablished
java.sql.SQLException: user lacks privilege or object not found: AGENCY_MASTER
at org.hsqldb.jdbc.Util.sqlException(Util.java:200)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(JDBCStatement.java:1805)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(JDBCStatement.java:205)
at coop.data.Connectionsetting.executeupdate(Connectionsetting.java:52)
at coop.data.Connectionsetting.main(Connectionsetting.java:116)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: AGENCY_MASTER
at org.hsqldb.Error.error(Error.java:76)
at org.hsqldb.SchemaManager.getTable(SchemaManager.java:510)
at org.hsqldb.ParserDQL.readTableName(ParserDQL.java:4367)
at org.hsqldb.ParserDML.compileInsertStatement(ParserDML.java:64)
at org.hsqldb.ParserCommand.compilePart(ParserCommand.java:132)
at org.hsqldb.ParserCommand.compileStatements(ParserCommand.java:83)
at org.hsqldb.Session.executeDirectStatement(Session.java:1037)
at org.hsqldb.Session.execute(Session.java:865)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(JDBCStatement.java:1797)
... 3 more
BUILD SUCCESSFUL (total time: 0 seconds)
Your connection URL looks iffy... try changing:
con=DriverManager.getConnection("jdbc:hsqldb:file"+db_file_name_prefix,"sa", "");
to
con=DriverManager.getConnection("jdbc:hsqldb:file:"+db_file_name_prefix+";ifexists=true","sa", "");
(adding a colon after "file", and appending the ifexists=true flag, as indicated by: http://hsqldb.org/doc/guide/ch04.html
It looks to me like the AGENCY_MASTER table doesn't exist. You're trying to execute an update statement, and it looks like HSQLDB can't find the AGENCY_MASTER table.
You can check whether the table exists with HSQLDB's built-in client/viewer:
java -cp hsqldb.jar org.hsqldb.util.DatabaseManagerSwing

Categories