Creating database and tables directly from Java - java

I'm trying to create the tables directly form Java instead of creating them using phpMyAdmin. The code looks like that runs smooth, but when the queries arrive, it gives some kind of error that I'm trying to identify and I'm not capable. Here's the code I've been trying:
package filmoteca;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class GestionBDD {
private static String datosConexion = "jdbc:mysql://127.0.0.1:3306/";
private static String baseDatos = "cine";
private static String usuario = "root";
private static String pass = "";
private static String tabla = "pelicula";
private Connection con;
public GestionBDD() {
try {
con = DriverManager.getConnection(datosConexion, usuario, pass);
try{
crearBDD();
crearTablas();
}catch(Exception e){
e.printStackTrace();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
public void crearBDD() throws Exception{
String query = "CREATE DATABASE IF NOT EXISTS"+ baseDatos +";";
Statement stat = null;
try{
stat = con.createStatement();
stat.executeUpdate(query);
con = DriverManager.getConnection(datosConexion+baseDatos, usuario, pass);
}catch(SQLException e){
e.printStackTrace();
}finally{
stat.close();
}
}
public void crearTablas() throws Exception{
String query = "USE DATABASE "+baseDatos+";"+
"CREATE TABLE IF NOT EXISTS"+" "+tabla+"("
+ "titulo VARCHAR(30), "
+ "director VARCHAR(30), "
+ "pais VARCHAR(30), "
+ "duracion FLOAT, "
+ "genero VARCHAR(30));";
Statement stat = null;
try{
stat = con.createStatement();
stat.executeUpdate(query);
con = DriverManager.getConnection(datosConexion+baseDatos, usuario, pass);
}catch(SQLException e){
e.printStackTrace();
}finally{
stat.close();
}
}
}

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

SQLException Operation not allowed after ResultSet closed

I am attempting to write a JUnit test for a query which is retrieved via a textbox in an html form. The text retrieval has been tested and works but my unit test is failing. I am using 2 relevant classes: QueryController and QueryControllerTest. I have been playing around with when and what I am closing in these two classes and keep getting the error: Operation not allowed after ResultSet closed.
QueryControllerTest.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import static org.junit.Assert.*;
public class QueryControllerTest {
#Test
public void testQuery() {
ResultSet testRs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String connectionUser = "root";
String connectionPassword = "GCImage";
conn = DriverManager.getConnection(connectionUrl,
connectionUser, connectionPassword);
Query testQuery = new Query();
testQuery
.setQuery("select * from service_request where FN_contact = 'Greg'");
testRs = QueryController.executeSelect(conn, testQuery);
assertEquals("Laughlin", testRs.getString("LN_contact"));
assertEquals("Hello World", testRs.getString("Notes"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
testRs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
QueryController.java
import java.util.Map;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class QueryController {
#RequestMapping(value = "/query")
public String processRegistration(#ModelAttribute("query") Query query,
Map<String, Object> model) {
String queryString = query.getQuery();
if (queryString != null && !queryString.isEmpty()) {
System.out.println("query (from controller): " + queryString);
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String connectionUser = "root";
String connectionPassword = "GCImage";
conn = DriverManager.getConnection(connectionUrl,
connectionUser, connectionPassword);
if (queryString.toLowerCase().startsWith("select")) {
ResultSet rs = executeSelect(conn, query);
} else {
int rowsUpdated = executeUpdate(conn, query);
System.out.println(rowsUpdated + " rows updated");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return "query";
}
public static ResultSet executeSelect(Connection conn, Query query) {
ResultSet rs = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query.getQuery());
while (rs.next()) {
String id = rs.getString("ID");
String firstName = rs.getString("FN_Contact");
String lastName = rs.getString("LN_Contact");
String notes = rs.getString("Notes");
System.out.println("ID: " + id + ", First Name: " + firstName
+ ", Last Name: " + lastName + ", Notes: " + notes);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rs;
}
}
QueryController.executeSelect is calling rs.close(), but then your assertEquals in QueryControllerTest.testQuery are calling methods on testRS. As executeSelect is returning the resultset, closing it first doesn't make sense. Further, executeSelect is being passed the connection, so it shouldn't be closing that either (what happens if the caller wants to do two different selects on the same connection?).
I think the problem is because you are creating two connections. Try to only instantiate the connection of QueryController class for your test. You will need to provide the connection. After you store it in a variable to run the query.
Connection con = QueryController.getConnection ();

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)

Record not getting deleted from MySQL database's table while it's deleted from Java GUI?

Edited Question
When I click the delete button, The row in the table gets deleted in GUI but not from database in mysql server.
Here's the code:
// DatabaseStore. This part runs fine.
public class DatabaseStore {
private final String server = "jdbc:mysql://localhost/";
private final String database = "music_magic";
private final String user_name = "root";
private final String pass_word = "";
private final String driver = "com.mysql.jdbc.Driver";
public Connection doConnection() {
Connection c;
try {
//load the driver
Class.forName(driver);
c = DriverManager.getConnection(server + database, user_name, pass_word);
// JOptionPane.showMessageDialog(null, "Database connected");
} catch (Exception e) {
c = null;
JOptionPane.showMessageDialog(null, "Error : " + e.getMessage());
}
return c;
}
//
// Imports
import Database_music.DatabaseStore; //main database page where i connect to database
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import magic_music.Items; //ignore this
//...
// Subject method
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(jTable1.getSelectedRow() >=0){
try{
DatabaseStore dtbs = new DatabaseStore();
Connection cn = dtbs.doConnection();
Statement stat = cn.createStatement();
String sql = "DELETE FROM products_info WHERE Product_id ='"+jTable1.getSelectedRow() +"'";
stat.executeUpdate(sql);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.removeRow(jTable1.getSelectedRow());
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
JOptionPane.showMessageDialog(null, "sql err");
}
} else {
JOptionPane.showMessageDialog(null, "Please select an item to delete");
}
}
Please tell me what am I doing wrong?

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

Categories