ClassNotFoundException Class.forName() in android - java

try {
String url = "jdbc:sqlserver://Aman\\SQL12;databaseName=P2C_Android";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, "sa", "aman");
String sql =
"select * from UserTable " +
"where username='" + username.getText().toString() +
"' and password='" + password.getText().toString() + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs != null && rs.next())
Toast.makeText(getApplicationContext(), "Redirecting...",
Toast.LENGTH_SHORT).show();
else {
Toast.makeText(getApplicationContext(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
attempts.setBackgroundColor(Color.RED);
counter-- ;
attempts.setText(Integer.toString(counter));
if(counter == 0)
login.setEnabled(false);
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(),
ex.getMessage(), Toast.LENGTH_SHORT).show();
}
It says class not found even when I can see that the class is present in sqljdbc.jar that I have added.
I am trying to access a database from an android application.

Make sure if you have only one version of JAR.
For ex-
You may have both sqljdbc.jar or sqljdbc4.jar in the classpath.

Related

Access is denied when I am executing an update query with Ucanaccess

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());
}

Error My SQL in Java Language (Netbeans)

I have code:
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
con = Connect.ConnectDB();
if (PatientID.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please retrieve Patient ID", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtNoOfDays.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please enter no. of days", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtServiceCharges.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please retrieve service charges", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtBillingDate.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please enter billing date", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtTotalPaid.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please enter total paid", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
double add1 = Double.parseDouble(txtRoomCharges.getText());
double add = Double.parseDouble(txtNoOfDays.getText());
double add2 = add * add1;
txtTotalRoomCharges.setText(String.valueOf(add2));
double add3 = Double.parseDouble(txtServiceCharges.getText());
double add5 = ((add * add1) + add3);
txtTotalCharges.setText(String.valueOf(add5));
double paid = Double.parseDouble(txtTotalPaid.getText());
txtTotalPaid.setText(String.valueOf(paid));
if (add5 > paid) {
double datadue = add5 - paid;
txtDueCharges.setText(String.valueOf(datadue));
}
//double add1 = Double.parseDouble(txtTotalCharges.getText());
//double add2 = Double.parseDouble(txtTotalPaid.getText());
Statement stmt;
stmt = con.createStatement();
String sql1 = "Select DischargeID from bill_room where DischargeID= " + txtDischargeID.getText() + "";
rs = stmt.executeQuery(sql1);
if (rs.next()) {
JOptionPane.showMessageDialog(this, "Record already exists", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
String sql = "insert into bill_room(DischargeID,BillingDate,RoomCharges,ServiceCharges,PaymentMode,PaymentModeDetails,ChargesPaid,DueCharges,TotalCharges,NoOfDays,TotalRoomCharges) values(" + txtDischargeID.getText() + ",'" + txtBillingDate.getText() + "'," + txtRoomCharges.getText() + "," + txtServiceCharges.getText() + ",'" + cmbPaymentMode.getSelectedItem() + "','" + txtPaymentModeDetails.getText() + "'," + txtTotalPaid.getText() + "," + txtDueCharges.getText() + "," + txtTotalCharges.getText() + "," + txtNoOfDays.getText() + "," + txtTotalRoomCharges.getText() + ")";
pst = con.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(this, "Successfully saved", "Record", JOptionPane.INFORMATION_MESSAGE);
btnSave.setEnabled(false);
} catch (HeadlessException | SQLException ex) {
JOptionPane.showMessageDialog(this, ex);
}
I have this code, when the execution runs (sometimes goes well, sometimes error.)
When error happen:
com.mysql.jdbc.exceptions.jbdc4.MySQLSyntaxErrorException" You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for right sysntax to use near
'110800.0,9,10800.0); at line 1
When Run clearly
What is not quite right here?
I need your help or your suggest
You already use PreparedStatement why you don't use it properly, so to avoid syntax error and SQL injection you can use :
String sql = "insert into bill_room(DischargeID, BillingDate, "
+ "RoomCharges, ServiceCharges, PaymentMode, PaymentModeDetails, "
+ "ChargesPaid, DueCharges, TotalCharges, NoOfDays, TotalRoomCharges) "
+ "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement insert = connection.prepareStatement(sql)) {
insert.setInt(1, txtDischargeID.getText());
insert.setString(2, txtBillingDate.getText());
//...Set the the right type if int use setInt if string use setString ...
insert.setDouble(11, Double.parseDouble(txtTotalRoomCharges.getText()));
insert.executeUpdate();
}
same thing with select.

Checking if username exists in MySQL Java

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.

Error-com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'BY'

private void UptadeSupplierActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
Class.forName(driver);
Connection con = DriverManager.getConnection(url, user, pass);
Statement st = con.createStatement();
ResultSet rec =st.executeQuery("SELECT SupName, SupSurName" +
"FROM Suppliers" +
"ORDER BY SupName");
while(rec.next())
{
System.out.println(rec.getString("SupName") + "," + rec.getString("SupSurName") + ".");
}
st.close();
}
catch(Exception e)
{
System.out.println("Error-" + e.toString());
}
}
You concatenate your strings like this:
"SELECT SupName, SupSurName" + "FROM SUPPLIERS"
This will result into:
SELECT SupName, SupSurNameFROM Suppiers
Note that you are missing a space between "SupSurName" and "FROM". Either add a " " (space) between your strings or simply add a space to the end of each string.

How to get column to equals according in database

I got problem with this on IFELSE statement
what i should i do? for equals of my position to database ACCESS
. I want to do is if the Admin is correct they show the CP and Staff is correct they show the AS for getting on position to my database.
addStudents AS = new addStudents();
ControlPanel CP = new ControlPanel();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager
.getConnection("jdbc:odbc:slcvJavaEnrollment");
Statement st = con.createStatement();
ResultSet rs = st
.executeQuery("SELECT * FROM loginUsers where Username='"
+ userTxt.getText() + "' and Password='"
+ passTxt.getText() + "'");
if (rs.getString("Position").contentEquals("Admin")) {
JOptionPane.showMessageDialog(null, "WELCOME ADMIN");
CP.show();
dispose();
con.close();
st.close();
} else if (rs.getString("Postion").contentEquals("Staff")) {
JOptionPane.showMessageDialog(null, "WELCOME STAFF");
AS.show();
dispose();
con.close();
st.close();
}
} catch (Exception e) {
System.out.println(e);
}
Your missing the while (rs.next()) to move the result set to the next result. Try this out. Also as #Learing pointed out, you spelled "Position" wrong in your else if.
while (rs.next()) {
if (rs.getString("Position").contentEquals("Admin")) {
JOptionPane.showMessageDialog(null, "WELCOME ADMIN");
CP.show();
dispose();
con.close();
st.close();
} else if (rs.getString("Position").contentEquals("Staff")) {
JOptionPane.showMessageDialog(null, "WELCOME STAFF");
AS.show();
dispose();
con.close();
st.close();
}
}
EDIT
To prevent SQL injection, you should use a PreparedStatment.
Try this instead of what you have
PreparedStatment pstmt = conn.prepareStatement("SELECT * from loginUsers WHERE Username=? and Password=?");
pstmt.setString(1, userTxt.getText());
pstmt.setString(2, passTxt.getText());
ResultSet rs = pstmt.executeQuery();

Categories

Resources