Run mysql function from a separate class - java

I have two "files". The main program and a separate class.
In the class I get some data from the database and output it. Now I want my main file to grab that and output in the form (in textbox). But I don't know how to take the variable or run the function/class from the main program.
Main:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
NewClass ha = new NewClass();
System.out.println(ha);
}
Class:
package kalorier;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author anton.jeppsson
*/
public class NewClass {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
String server = "localhost:3306";
String password = "root";
String user = "root";
String db = "cms";
String connectionString = "jdbc:mysql://" + server + "/" + db + "?user=" + user + "&password=" + password;
System.out.println("Connecting with " + connectionString);
conn = DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
String ha = rs.getString("user_name");
System.out.println(ha);
}
}
}

Probably something like this:
Button actionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
NewClass ha = new NewClass();
for (String user : ha.doDatabaseStuff())
{
System.out.println(user);
}
}
NewClass
public class NewClass {
public static void main(String[] args) {
//Maybe do other stuff here, or is this method even necessary?
}
public List<String> doDatabaseStuff() {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
String server = "localhost:3306";
String password = "root";
String user = "root";
String db = "cms";
String connectionString = "jdbc:mysql://" + server + "/" + db + "?user=" + user + "&password=" + password;
System.out.println("Connecting with " + connectionString);
conn = DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
List<String> results = new ArrayList<>();
while (rs.next()) {
results.add(rs.getString("user_name"));
}
return results;
}
}

Related

while executing update statement by jdbc on Oracle dbms, my program hangs or waits

While executing update by jdbc on Oracle dbms, my program hangs. I think it is waiting for another process/user to release lock on the rows or table that I am trying to update. So what are the possible causes for this problem and how can I solve it?
I am making calls to the dbms through jdbc as show here:
public static void updateEmployee(String name,int id) throws ClassNotFoundException
{
Connection con=null;
PreparedStatement st=null;
String driver= "oracle.jdbc.driver.OracleDriver";
String username="someuser";
String password="pwd";
String url="jdbc:oracle:thin:#hostname:1521:ORAJAVADB";
Class.forName(driver);
try
{
con=DriverManager.getConnection(url,username,password);
st=con.prepareStatement("update employee set employeeName=? where
employeeId = ? ");
st.setString(1,name);
st.setInt(2,id);
st.executeUpdate();
st.close();
con.close();
}
catch(SQLException ex)
{
}
}
I made this code for update function using java with oracle database. I hope it will help you. Good Luck
package updatemethod;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.pool.OracleDataSource;
public class UpdateMethod {
public static String url = "jdbc:oracle:thin:#mohammed:1521:XE";
public static String user = "md";
public static String password = "md";
public static String query;
public static Connection conn;
public static Statement smt = null;
// CREATE DATABASE CONNECTION
public static void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(url);
conn = ds.getConnection(user, password);
System.out.println("DataBase Accessed!");
}
public static void updateEmployee(String nID, String newFirst, String newLast, String newJob)throws SQLException{
try{
smt = conn.createStatement();
smt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = smt.executeQuery("SELECT ID, FIRSTNAME, LASTNAME, JOB FROM MD.EMPLOYEE1");
while(uprs.next()){
int newID = Integer.parseInt(nID);
uprs.updateInt("ID", newID);
uprs.updateString("FIRSTNAME", newFirst);
uprs.updateString("LASTNAME", newLast);
uprs.updateString("JOB", newJob);
uprs.updateRow();
System.out.println("DataBase Updated\n");
System.out.println("ID " + newID + " " + "FIRSTNAME " + newFirst + " " + "LASTNAME " + newLast + " " + "JOB " + newJob);
}
}
catch(SQLException er){
System.out.println(er);
}
}
public static void main(String[] args) throws SQLException {
// CREATE CONNECTION BY CALLING getDBConnection();
getDBConnection();
// NOW, CALL OUR updateEmployee(String,String,String,String) FUNCTION
updateEmployee("123", "mohammed", "Jamal", "Computer Technique Engineer");
}
}

SQL connection : can't connect to database in java

I have added JAR file "mysql-connector-java-5.1.36-bin" and have created database "UserScore" and under that table "ScoreSheet".I have added a row in ScoreSheet (Name,Score) value ('Kamal',40) to verify but the code throws a lot of exceptions on connection.I am using Eclipse + Xampp.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class SQLDriver{
public static void main(String[] args){
try{
//Accessing driver from jar file
Class.forName("com.mysql.jdbc.Driver");
//Get connection through creating a variable 'myConn'
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/UserScores");
//Create statement
PreparedStatement statement = myConn.prepareStatement("select * from 'scoresheet'");
//Execute SQL Query
ResultSet result = statement.executeQuery();
//Process the result set
while(result.next()){
System.out.println(result.getString(1)+" "+result.getString(2));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
I always do it like this:
// Hostname
private static final String dbHost = "127.0.0.1";
// Port -- Standard: 3306
private static final String dbPort = "3306";
// Database name
private static String database = "database"; //
// Database user
private static final String dbUser = "root";
// Datenbankpasswort
private static final String dbPassword = "";
private Statement s;
public void Connect() {
try {
Class.forName("java.sql.Driver"); // load driver
Connection conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":"
+ dbPort + "/" + database + "?" + "user=" + dbUser + "&"
+ "password=" + dbPassword); // try to connect with your attributes
s = conn.createStatement();
} catch (ClassNotFoundException e) { //
l.error("Driver not found " + e);
} catch (SQLException e) {
l.error("Connect not possible" + e);
}
}
Your query should specify Scoresheet without '
Specify the username and password when calling DriverManager.getConnection
The second row in your table does not appear to be of type string. Invoke result.getInt(2) rather than result.getString(2)

While calling the below function control is going to the first line inside try block i.e to Class.forName then to catch block

package com.java.bean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Dao {
// static Connection con = null;
static ResultSet rs = null;
static String url ="jdbc:mysql://localhost:3306/first";
static String user = "root";
static String passsword = "password";
public static Ex1 login(Ex1 ex){
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.driver");
Connection con = DriverManager.getConnection(url,user,passsword);
String userName = ex.getUserName();
String password = ex.getPassword();
Statement st = con.createStatement();
rs = st.executeQuery("Select * from employee where username = " +userName +"and password =" +password );
boolean more = rs.next();
if(!more)
{
System.out.println("you are not a registered user!");
ex.setValid(false);
}
else if(more)
{
System.out.println("welcome MR.HImanshu you are Great");
ex.setValid(true);
}
}
catch(Exception tex)
{
System.out.println("hey there is an exception " +ex);
}
return ex;
}
}
Is
Class.forName("com.mysql.jdbc.Driver");
not
Class.forName("com.mysql.jdbc.driver");
"Driver" with an uppercase "D".

How to export a table from mysql using java

I need to export a table from mysql using java. I tried using
public class automateExport {
public static void main(String[] argv) throws Exception {
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
String serverName = "192.168.0.189";
String mydatabase = "ArchiveIndexer";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
String filename = "c:/outfiless.txt";
String tablename = "D_Centre";
System.err.println("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
stmt.executeUpdate("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
// stmt.executeQuery("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
// stmt.execute("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
}
}
But this is throwing error like
"Exception in thread "main" java.sql.SQLException: Can not issue SELECT via executeUpdate().
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1764)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1725)
at automateexceldatabase.automateExport.main(automateExport.java:38)
Java Result: 1"
This will help:
public class DatabaseToCSV {
public static void main(String[] args) {
String filename =
"C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase\\myjdbcfile.csv";
try {
FileWriter fw = new FileWriter(filename);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(
"jdbc:mysql://192.168.0.189:3306/ArchiveIndexer"
, "username"
, "password"
);
String query = "select * from D_Centre";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append(',');
fw.append(rs.getString(4));
fw.append('\n');
}
fw.flush();
fw.close();
conn.close();
System.out.println("CSV File is created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
this might help u : Export database to csv file
Example below exports data from MySQL Select query to CSV file.
testtable structure
CREATE TABLE testtable
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
text varchar(45) NOT NULL,
price integer not null);
Application takes path of output file as an argument.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class automateExport {
public static void main(String[] args) {
DBase db = new DBase();
Connection conn = db.connect(
"jdbc:mysql://localhost:3306/test","root","caspian");
if (args.length != 1) {
System.out.println(
"Usage: java automateExport [outputfile path] ");
return;
}
db.exportData(conn,args[0]);
}
}
class DBase {
public DBase() {
}
public Connection connect(String db_connect_str,
String db_userid, String db_password) {
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(db_connect_str,
db_userid, db_password);
} catch(Exception e) {
e.printStackTrace();
conn = null;
}
return conn;
}
public void exportData(Connection conn,String filename) {
Statement stmt;
String query;
try {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//For comma separated file
query = "SELECT id,text,price into OUTFILE '"+filename+
"' FIELDS TERMINATED BY ',' FROM testtable t";
stmt.executeQuery(query);
} catch(Exception e) {
e.printStackTrace();
stmt = null;
}
}
};
The error means that you are using executeUpdate() when you should be using executeQuery()
executeUpdate() is for executing updates (duh)
executeQuery() is for searching the database and returning a ResultSet
Hope this helps

java.sql.SQLException: No suitable driver found

I am trying to execute simple query using below DbQuery.java class which uses DbConnector to get a Connection from DriverManager.
note:
I have already included "mysql-connector-java-5.1.25-bin.jar" on my
classpath via: export
CLASSPATH=$CLASSPATH:/home/me/ocpjp/chapter-10/mysql-connector-java-5.1.25/mysql-connector-java-5.1.25-bin.jar
I am able to connect to mysql with "mysql -uroot -ptcial
addressBook", if it matters.
have also tried running with '-cp'
argument with no avail.
I am able to get my #3 DbConnect.java class to say "Database connection established".
Also #4 DbQueryWorking.java has no issues and provides expected output .
Can you please help me understand what is the issue here ?
1) DbConnector.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnector{
public static Connection connectToDb() throws SQLException{
String url = "jdbc:mysql//localhost:3306/";
String db = "addressBook";
String username = "root";
String password = "tcial";
return DriverManager.getConnection(url+db, username, password);
}
}
2) DbQuery.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import com.me.ocpjp.chapter10.DbConnector;
public class DbQuery{
public static void main(String[] args){
try(Connection connection = DbConnector.connectToDb();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
3) DbConnect.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConnect{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url+database, userName, password)){
System.out.println("Database connection established");
}catch(Exception e){
System.out.println("Database connectioni NOT established");
e.printStackTrace();
}
}
}
4) DbQueryWorking.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import java.sql.DriverManager;
public class DbQuery{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url + database, userName, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
it looks like that the URL in DbConnector.java is wrong. A colon is missing. The url must be:
jdbc:mysql://localhost:3306/
and not
jdbc:mysql//localhost:3306/
your URL is wrong, you're missing a colon in it, it should be:
String url = "jdbc:mysql://localhost:3306/";

Categories