How to confirm the insert query is a success? - java

I am inserting into the database with foll0wing code and it's working fine as I can see the data populates in the db, however I want to capture the result programmatically whether it was a success or failure
1) Here is the code to insert
public void SignUp(String last_name, String first_name, String email,
String password, String confirm_password, String phone) {
Connect connect = new Connect();
Connection conn = connect.Connection();
Statement stmt = conn.createStatement();
String query = "INSERT INTO users VALUES(NULL,('" + last_name + "'),('"
+ first_name + "'),('" + email + "'),('" + password + "'),('"
+ confirm_password + "'),('" + phone + "'))";
stmt.executeUpdate(query);
conn.close();
}
2) Here is the code I used to connect
public Connection Connection() {
Connection conn = null;
try {
String userName = "admin";
String password = "admin";
String url = "jdbc:mysql://localhost/project";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
System.out.println("\n Database connection established");
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n Cannot connect to database server");
}
}

executeUpdate
public int executeUpdate(String sql)
throws SQLException
Returns: either the row count for INSERT, UPDATE or DELETE statements,
or 0 for SQL statements that return nothing

The simplest way would be to query for it directly. Its always a good idea to check the API, but with an update I am not sure that barring an exception there is a clean way to tell if it was successful (other than a lack of exceptions being thrown).
As a side note, take a look at Prepared Statements. It is generally not a good idea to use strait text when executing un-sanitized sql.

Related

How to check if a row exist in the SQLite table with a condition

I am using SQLite local database in my software. I want to check if a row exists based on the giver values of the row. for example : "SELECT * FROM ftp WHERE Host LIKE '"+ host +"' AND Username LIKE '"+ username +"' "
But I want to get boolean result so if finds the record do something and if not do something else. Hoe can I do this?
here is what I tired but it is always true, since it check if quesry runs and not if it returns data.
public void ftpTableCheck(String host, String port, String username, String password){
try{
String query = "SELECT * FROM ftp WHERE Host LIKE '"+ host +"' AND Username LIKE '"+ username +"' ";
PreparedStatement pst = conn.prepareStatement(query);
if (pst.execute() == true){
System.out.println("true");
}
}catch(Exception e){
e.printStackTrace();
}
}
Any idea how to fix it?
Thanks
So, you can use something like select count(*) ... or select (count(*) > 0) as found ... as the base query.
When you call executeQuery, you will get a ResultSet in return, from this, you need to determine it's contents.
In your case, you are only expecting a single row result, so you can simply use ResultSet#next to move to the first row and then extract the column value from it...
public void ftpTableCheck(String host, String port, String username, String password) {
try {
String query = "SELECT (count(*) > 0) as found FROM ftp WHERE Host LIKE ? AND Username LIKE ?";
PreparedStatement pst = conn.prepareStatement(query);
pst.setString(1, host);
pst.setString(2, username);
try (ResultSet rs = pst.executeQuery()) {
// Only expecting a single result
if (rs.next()) {
boolean found = rs.getBoolean(1); // "found" column
if (found) {
// You have rows
} else {
// You have no rows
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Take a closer look at JDBC Database Access and Using Prepared Statements for more details
The general method to do this is to fetch the results and check if it is not empty. For your question, it will be logical to count the returned rows.
As #MadProgrammer said, query like:
String query = "SELECT COUNT(*) FROM ftp WHERE Host LIKE '"+ host +"' AND Username LIKE '"+ username +"' ";
Now you just have to get the count and check if it is 0 (NOT FOUND) or not (FOUND)

MySQL query for insert

I am trying to insert into my MYSQL database but my code always go to the catch section (which says uploading to database failed). What am I doing wrong?
public static Connection getAttConnection() throws Exception {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "VB";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "***********";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
return conn;
}
public static void addAttendance(String name, String type, String size,
String path, String last_Mod) {
Connection conn = null;
PreparedStatement pstmt = null;
boolean committed = false;
try {
conn = getAttConnection();
conn.setAutoCommit(false);
String query = "INSERT INTO upload (name, type, size, path, last_Mod) VALUES (?,?,?,?,?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1,name);
pstmt.setString(2,type);
pstmt.setString(3,size);
pstmt.setString(4,path);
pstmt.setString(5,last_Mod);
pstmt.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
committed = true;
System.out.println("Upload Correctly");
} catch (Exception e) {
System.err.println("Uploading to database failed");
}
}
Is your password supplied correctly? Your code shows its all "*"
Next, check the Database name.
Then, instead of printing a custom message, print the entire exception, like this:
e.printStackTrace(System.out);
Not totally sure but you are probably inserting strings without quotes....
String query = "INSERT INTO upload (name, type, size, path,
last_Mod) VALUES ('?','?','?','?','?')";
You are passing all the parameters as strings, but I suspect size should be an int.
I suspect that there might be a problem with data types, e.g. when you do
pstmt.setString(3, size);
Are you sure that size is a String in your database table?
Also, please add
e.printStackTrace();
to your catch() clause to get a more detailed error message.

How to access the another system mysql database through java program?

How to access the another system mysql database through java program?Am using the following program but i have get the communication error?what are the changes are need to connect the another system mysql database?
Public void dbconnection() {
String name = "";
String port = "3306";
String user = "system";
String pass = "system";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
You're not creating an instance of the driver class:
Class.forName("com.mysql.jdbc.Driver").newInstance();
[update: not necessary after all, ignore that]
And you're also referencing "sun.jdbc.odbc.JdbcOdbcDriver", is that necessary? If so, shouldn't you instantiate it also? [update: probably not]
If it works with localhost, and not with the IP specified, you need to configure mysql to listen on all ports.
jcomeau#intrepid:/tmp$ cat dbconnection.java; javac dbconnection.java; sudo java -cp .:/usr/share/maven-repo/mysql/mysql-connector-java/5.1.16/mysql-connector-java-5.1.16.jar dbconnection
import java.sql.*;
public class dbconnection {
public static void main(String args[]) {
String name = "";
String port = "3306";
String user = "root";
String pass = "";
String dbname = "imagetagging";
String host="127.0.0.1";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from taggers";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
URL:jdbc:mysql://127.0.0.1:3306/imagetagging
Name:1
Name:2
Name:3
Name:4
Name:5
Name:6
Name:7
Name:8
Name:9
Name:10
Name:11
Name:12
Name:13
Name:14
Name:15
Name:16
Name:17
Name:18
Name:19
Name:20
Name:21
As I understand you just need to specify another connection string, with another host and other credentials, e.g.:
...
String port = "3306";
String user = "user_name";
String pass = "password";
String dbname = "db_name";
String host="host_name";
...
You have to do 3(with 4th step optional) simple things to connect to your remote mysql database server.
Open up any GUI tool for mysql database management (your IDE, Mysql Workbench or smth else), check if you can connect to your database by specifying your credentials, host, port and database name.
If that succeeds you know there is nothing wrong on the db part (go to 3), if not, and you are sure you do everything correctly up to this point go to point 2.
check out this post on how to enable remote access to your db and try again (go to pkt 1)
You would have to clean up a bit your code, have a look into simple and to the point tutorial on how to connect and execute simple sql statements with java on Vogella tutorial
Once everything is working correctly, remember to give +1 on Vogella tutorial, praise the cybercity or any other website for the explanation on how to enable remote access on you db and don't forget to come back to stackoverflow and reward all good answers :)

How to create and execute an SQL update statement

I have a table inside consist of variable like Username, ContactNo, Date, Name.
And i would like to do a update for Username and ContactNo only to the original record in the database.
How can i make use of update sql statement to do it?
Below is my SELECT sql statement.
public void dbData(String UName)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/assignment","root","mysql");
ps = con.createStatement();
SQL_Str="Select username,numberOfBid from customer where username like ('" + UName +"')";
//SQL_Str="Select * from customer";
rs=ps.executeQuery(SQL_Str);
rs.next();
dbusername=rs.getString("username").toString();
dbbid=rs.getInt("numberOfBid");
//UName2 = rs.getString("username").toString();
UName2 = username;
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occur :" + ex);
}
}
http://dev.mysql.com/doc/refman/5.0/en/update.html
And please study...
Here is a quick and dirty solution: when you have modified your values, just add something like this
String updSQL = "udate table set numberOfBid = " + dbbid + " where user = " + UName;
ps.executeUpdate(updSQL);
There are however 1000 improvements you can make such using prepared statementsand placeholders:
String updSQL = "udate table set numberOfBid = ? where username like ?";
PreparedStatement pstmt = con.prepareStatement(updSQL);
pstmt.setInt(0, dbbid);
pstmt.setString(1, UName);
pstmt.execute();
May I suggest you to have a look at Hibernate, Spring JDBC, JPA... which are on a much higher level than JDBC is.

connecting to database

can anyone help me how to connect my java forms to my mysql database?
i have this following codes but it didn't work...
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
String value1 = textField1.getText();
String value2 = textField2.getText();
String value3 = textField3.getText();
String value4 = textField4.getText();
Connection con = null;
String url = "jdbc:mysql://localhost:3306/Marketing";
String driver = "com.mysql.jdbc.Driver";
String db = "Marketing";
String user = "root";
String pass = "";
System.out.println(value1 + value2 + value3 + value4);
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
PreparedStatement st = con.prepareStatement("insert into clients (idclients, name, address, contact_person, contact_num) values(?,?,?,?,?)");
st.setString(2, value2);
st.setString(3, value3);
st.setString(4, value4);
st.executeUpdate();
JOptionPane.showMessageDialog(jPanel1, "Data is successfully inserted into database.");
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(jPanel1, "Error in submitting data!");
}
}
One problem I can see straight away is that your PreparedStatement expects 5 parameters (1 - 5) yet you're only setting 3!
Secondly, I'm not sure why you use DriverManager.getConnection( url +db , ... ) when your database URL already contains a database name, so use just DriverManager.getConnection(url,user,pass).
Having said that though, it would be good if you could clarify what exactly doesn't work?
There is problem with connection code :
url = jdbc:mysql://localhost:3306/Marketing
db = Marketing
url + db = jdbc:mysql://localhost:3306/MarketingMarketing
here you have to remove one extra marketing
The error is in this statement:
con = DriverManager.getConnection(url + db, user, pass);
The getConnection method connect to database on url specified in 1st parameter. Here you combine 2 variables named url and db so your connection url will become: jdbc:mysql://localhost:3306/MarketingMarketing which may be not the thing you want. Use only url instead of url + db.

Categories