I have just started with ucanaccess and I am attempting to work out how it works. I wanted to update my Access database's username from "Sutaciba" to "Evan" but it shows the following error:
"Exception occured:
UCAExc:::4.0.4 C:\Users\evanc\AppData\Roaming\IT PAT DataBase (Access is denied)".
Seems like Ucanaccess doesn't have permission to gain access to my database for some reason.
Thank you for any help!
public static void main(String args[])
{
int ID = 1;
String username = "Sutachiba";
String password = "Evanchui123";
String email = "evanchui34#gmail.com";
try
{
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\evanc\\AppData\\Roaming\\IT PAT DataBase");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [username], [password] FROM [tblUser] WHERE ID =" + ID);
while(rs.next())
{
username = rs.getString(1);
password = rs.getString(2);
email = rs.getString(3);
System.out.println("Username: " + username + '\n' + "Password: " + '\n' + "Email:" + email);
}
String newN = "Evan";
String updateQuery = "UPDATE userDB SET (username) = (?) WHERE ID =" + ID;
PreparedStatement st = conn.prepareStatement(updateQuery);
st.setString(1, newN);
st.executeUpdate();
System.out.println("Successfully updated userdata!");
conn.close();
}
catch(Exception ex)
{
System.err.println("Exception occured: ");
System.err.println(ex.getMessage());
}
Related
Have sqlite table named good_in with columns in_id, good_code, in_group, in_quantity, in_VATPaid
Here is my table example
and have method to insert records into it
public static void inputGoods(GoodsInput goodsinput){
String goodCode = goodsinput.getInGood().getGood_code();
int goodBatch = goodsinput.getInGroup();
int goodQuantity = goodsinput.getInQuantity();
double goodVATPaid = goodsinput.getInVatPaid();
String sqlInsert = "INSERT INTO good_in (good_code, in_group, in_quantity, in_VATPaid)"
+ " VALUES ('" + goodCode + "', " + "'" + goodBatch + "', " + "'" + goodQuantity
+ "', " + "'" +goodVATPaid + "');";
System.out.print(sqlInsert);
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
statement.executeUpdate(sqlInsert);
}
catch(SQLException e){
}
}
Connection class
public static Connection ConnectDB(){
try{
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:kahuyq.db");
return con;
} catch (HeadlessException | ClassNotFoundException | SQLException ex){ JOptionPane.showMessageDialog(null, ex); }
return null;
}
When I copy the printed query to sqlite manager it adds the row, but from java it ends program with no error but does not add row to my table.
What is wrong?
Have also other method that checks weather the good_code exists in table good which have only 2 columns id and good_code and if does not exist adds it. this method is accessed from GoodsInput constructor. When I delete the method from constructor the other method works fine.
Here is that method
public static void insertGoods(Good g){
String sqlSelect = "Select * from good where good_code = '"
+ g.getGood_code() + "'" ;
String sqlInsert = "INSERT INTO good (good_code)"
+ "VALUES ('" + g.getGood_code() +"')";
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sqlSelect);
while(!rs.next()){
statement.executeUpdate(sqlInsert);
break;
}
}
catch(SQLException e){
}
}
Try to add
conn.commit();
after the execution of your statement.
Everything just worked don't know what I did ,but I keep getting the error when wanting to UPDATE information in my SQL database. Error : The column position '1' is out of range. The number of columns for this ResultSet is '0'
try
{
String em = EmailField.getText();
String na = NameField.getText();
String su = SurnameField.getText();
String i = IDField.getText();
String ce = CellField.getText();
String query2 = "UPDATE LouwDataBase.Table1Test "
+ "SET Email = "+"'"+em+"'"+" , "
+ "Name = "+"'"+na+"'"+" , "
+ "Surname = "+"'"+su+"'"+" , "
+ "ID = "+"'"+i+"'"+" , "
+ "Cell = "+"'"+ce+"'"
+ " WHERE Email = "+"'"+UserEmailID+"'";
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
stat = conn.createStatement();
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(query2))
{
pstmt.setString(1, em);
pstmt.setString(3, na);
pstmt.setString(4, su);
pstmt.setString(5, i);
pstmt.setString(6, ce);
pstmt.executeUpdate();
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
Since you're using PreparedStatement, I think you need to have question marks in the query and then use pstmt.setString().
try {
String em = EmailField.getText();
String na = NameField.getText();
String su = SurnameField.getText();
String i = IDField.getText();
String ce = CellField.getText();
String query2 = "UPDATE LouwDataBase.Table1Test "
+ "SET Email = ?, "
+ "Name = ?, "
+ "Surname = ?, "
+ "ID = ?, "
+ "Cell = ?"
+ " WHERE Email = ?";
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
stat = conn.createStatement();
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(query2)) {
pstmt.setString(1, em);
pstmt.setString(3, na);
pstmt.setString(4, su);
pstmt.setString(5, i);
pstmt.setString(6, ce);
pstmt.executeUpdate();
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
}
I have a register dialog that implements an action listener. If a user enters a name and it already exists, I want to print a message on the console. If the username does not exist, MySQL should add it into the database. Unfortunately this code won't work:
private void regButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(!userBox.getText().equals(""))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/genx", "root", "Warlock1989");
Statement stmt = con.createStatement();
String query = "SELECT name FROM accounts";
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
String uname = rs.getString("name");
if(!uname.equals(userBox.getText()))
{
PreparedStatement pstmt = con.prepareStatement("INSERT INTO accounts(name) VALUES(?)");
pstmt.setString(1, userBox.getText());
pstmt.executeUpdate();
System.out.println("Username " + userBox.getText() + " has been registered.");
}
else
{
System.out.println("Username " + userBox.getText() + " already exists.");
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Your current approach loads all records from database and tries to find the user which will cause memory exceptions if the database consists of huge records. So,
Do not fetch all records from database rather simply run the query using where name=? to check user already exists in the database as shown below:
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
ResultSet rs = null;
try {
String userInput = userBox.getText();
String query = "SELECT name FROM accounts where name=?";
pstmt1 = con.preparedStatement(query);
pstmt1.setString(1, userInput);
rs = pstmt1.executeQuery();
if(rs.next()) {
pstmt2 = con.prepareStatement("INSERT INTO accounts(name) VALUES(?)");
pstmt2.setString(1, userInput);
pstmt2.executeUpdate();
System.out.println("Username " + userInput + " has been registered.");
} else {
System.out.println("Username " + userInput + " already exists.");
}
} catch(SQLException sqlexe) {
//add logging
} finally {
if(pstmt1 != null)
pstmt1.close();
if(pstmt2 != null)
pstmt2.close();
if(rs != null)
rs.close();
}
Your current code does not release the resultsset & preparedstatement objects, so ensure that you are releasing the resources in the finally block.
When I write a name as a user, I need to access the surname for this name which is already in database. For example:
Enter a name: beste
beste's surname is: ozcaglar
When I execute my code I can't see any surname as output.
In my database, I have name, surname and no (Auto-Incremented) columns.
import java.sql.*;
import java.util.*;
public class ConnectionMySQL {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a name: ");
String isim = scan.next();
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/student","root","");
//System.out.println("Connection success");
String query= "SELECT surname FROM student_table WHERE name='isim'";
Statement stm =conn.createStatement();
ResultSet rs= stm.executeQuery(query);
while (rs.next()) {
System.out.println("Name: " + rs.getString("name")+ " Surname: "+rs.getString("surname"));
}
}
catch (Exception e) {
System.err.println(e);
}
}
}
You can follow this:
import java.sql.*;
import java.util.*;
public class test4 {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("Enter a name: ");
String isim = scan.next();
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
System.out.println("Connection success");
String query = "SELECT * FROM users WHERE surname='" + isim + "'";
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
String fName = rs.getString(1);
String sName = rs.getString(2);
System.out.println("Name: " + fName + " Surname: " + sName);
}
} catch (Exception e) {
System.err.println("Error");
}
}
}
The error means that the table doesn't have a column that is called "isim".
Maybe you meant to write:
SELECT surname FROM student_table WHERE name='isim'
?
EDIT (following the comments):
query = "SELECT surname FROM student_table WHERE name='" + isim + "'"
However this should not be used in a real-world application for security reasons (it allows SQL injection attacks).
In actual production code you should either escape input strings, or use parameterized queries...
I am trying to create a generic method that can add an entry into a SQLite database, using Eclipse and Java.
When the table name is hardcoded it works fine, but when I try to pass in the table name as a string it is giving me a nullPointerException.
below is the method that creates that table:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS COMPANY " +
"(ID INT PRIMARY KEY NOT NULL," +
" NAME TEXT NOT NULL, " +
" AGE INT NOT NULL, " +
" ADDRESS TEXT, " +
" SALARY REAL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created successfully");
}
and here is the method that inserts an entry into the created table. I want to pass in the table name through the method rather than hard coding it:
public static void Insert(String table, int id, String name, int age, String address, String salary)
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query="INSERT INTO "+table+" (ID,NAME,AGE,ADDRESS,SALARY) VALUES (?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(query);
pstmt.setInt(1,id);
pstmt.setString(2,name);
pstmt.setInt(3, age);
pstmt.setString(4, address);
pstmt.setString(5, salary);
pstmt.executeUpdate();
pstmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}
You have small mistake
just you have created two different PreparedStatement object
So change
PreparedStatement stmt = c.prepareStatement(query);
to
pstmt = c.prepareStatement(query);