connecting to database - java

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.

Related

Where do I specify the database name in the getTables() method.

The getTables() method is not returning any results for a table that exists in the database. I think the trouble is that is doesn't know which database to look at on the ip. How do I specify which database the getTables() method is supposed to be looking in as I have multiple databases with the same tables?
//concatinating strings for IP to hit
String ArchiveDB_URL = "jdbc:sqlserver://" + getArchiveIPaddress();
// Database credentials
String USER = "Removed";
String PASS = "Removed";
Connection archiveConn = null;
Statement archiveStmt = null;
try {
// Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Open a connection
archiveConn = DriverManager.getConnection(ArchiveDB_URL, USER, PASS);
DatabaseMetaData dbm = archiveConn.getMetaData();
ResultSet rsTBmd = dbm.getTables(null,null, "[myDatabase].[dbo].[myTable]", new String[] {"TABLE"});
System.out.println(rsTBmd.getString("TABLE_NAME"));
if (rsTBmd.next()){
//result sets start at 1 not 0
int rsTBmdi = 1;
while(rsTBmd.next()){
System.out.println(rsTBmd.getString(rsTBmdi));
rsTBmdi++;
}
}
The first two arguments of getTables are catalog and schemaPattern. "Catalog" is another name for "Database", so just supply the database name as the first argument:
ResultSet rsTBmd = dbm.getTables("myDatabase", "dbo", "myTable", new String[] {"TABLE"});
Note that in this case you do not enclose the names in square brackets, even if they contain spaces or "funny characters".
According to Microsoft, your JDBC URL looks like "jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks;user=UserName;password=*****";, making your code:
// Database credentials
String USER = "Removed";
String PASS = "Removed";
Connection archiveConn = null;
Statement archiveStmt = null;
try {
// Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Open a connection
//concatinating strings for IP to hit
String ArchiveDB_URL = "jdbc:sqlserver://" + getArchiveIPaddress() + ";database=myDatabase;username="+USER+";password="+PASS;
archiveConn = DriverManager.getConnection(ArchiveDB_URL);
DatabaseMetaData dbm = archiveConn.getMetaData();
ResultSet rsTBmd = dbm.getTables(null,null, "[myDatabase].[dbo].[myTable]", new String[] {"TABLE"});
System.out.println(rsTBmd.getString("TABLE_NAME"));
if (rsTBmd.next()){
//result sets start at 1 not 0
int rsTBmdi = 1;
while(rsTBmd.next()){
System.out.println(rsTBmd.getString(rsTBmdi));
rsTBmdi++;
}
}
I do hope this helps...
Try adding the database name in the ArchiveDB_URL
String ArchiveDB_URL = "jdbc:sqlserver://" + getArchiveIPaddress() + "/yourDatabaseNameHere";

Search for id through database table Java not working

I am trying to understand why I can not search more than one record in a database with Java. It is a Java jsp application but I seems to struggle to figure out where the issue is. I am a beginner with jsp but I am sure would not make any difference
try{
String myDriver = "org.gjt.mm.mysql.Driver";//db driver
String myUrl = database;//connect to db
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, user, password);//authenticating on database
String query = "SELECT Cus_ID, Cus_name, Cus_surname, Cus_mail, Cus_Address, Cus_telephone FROM customerdb";//mysql select statement
PreparedStatement sta = conn.prepareStatement(query); //prepared statement
ResultSet rst = sta.executeQuery(query);
while (rst.next())
{
String cusid = rst.getString("Cus_ID"); //variable to retrieve the customer from the database
String cusn = rst.getString("Cus_name");
String cussn = rst.getString("Cus_surname");
String cusm = rst.getString("Cus_mail");
String cusaddr = rst.getString("Cus_Address");
String custel = rst.getString("Cus_telephone");
if(!(customer.equals(cusid))){
request.setAttribute("al", "user not found");
request.getRequestDispatcher("account.jsp").forward(request, response); //and user will stay on login page
}if(customer.equals(cusid)){
System.out.println("hello" + cusid);
request.setAttribute("ID", cusid);
request.setAttribute("name", cusn);
request.setAttribute("surname", cussn);
request.setAttribute("mail", cusm);
request.setAttribute("address", cusaddr);
request.setAttribute("telephone", custel);
request.getRequestDispatcher("account.jsp").forward(request, response);
}else{
}
}
}catch(ClassNotFoundException | SQLException | HeadlessException ex) {
Logger.getLogger(LogInController.class.getName()).log(Level.SEVERE, null, ex);
}
The PreparedStatement#executeQuery() method does not take any parameters. Change this:
ResultSet rst = sta.executeQuery(query);
to this:
ResultSet rst = sta.executeQuery();
This is a somewhat common mistake when using this API. You may have other issues with your code as well, but this should make a noticeable improvement.

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 confirm the insert query is a success?

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.

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 :)

Categories