This is a program for updating a table using jdbc and it compiled successfully.
But at runtime gives error.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class UpdateProfile {
public static void main(String args[]) {
String fname = "ranjesh";
String lname = "singh";
String phone = "9870899645";
String address = "ghz";
String email = "sarwesh1206#gmail.com";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE", "system", "oracle");
//system is username and oracle is password
//userinfo is name of table.
String query = "UPDATE userinfo set fname = ? ,lname=?,mobile=?,address=? where email = ? ";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, fname); // set input parameter 1
pstmt.setString(2, lname);
pstmt.setString(3, phone);
pstmt.setString(4, address);
pstmt.setString(5, email);
// set input parameter 2
pstmt.executeUpdate(); // execute update statement
con.commit();
con.close();
System.out.print("success");
} catch (Exception ex) {
System.out.print("error occurred");
}
}
}
Schema of table userinfo:
Related
I am trying to connect my HTML Login page with the database. I wrote this servlet but facing some error in the connection.
String name=request.getParameter("uname");//Passing the HTML tag to he string
String psw= request.getParameter("psw");//
String QUERY="SELECT *FROM login WHERE EMAIL=?,PASS=?"; //Query
Class.forName("com.mysql.jdbc.Driver");//Connection
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost/SmallERP", "root", "root")) {
PreparedStatement ps = con.prepareStatement(QUERY);
ps.setString(1, name);
ps.setString(2, psw);
try (ResultSet rs = ps.executeQuery()) {
if(rs.next()){
out.println("Done");
}else{
out.println("ERROR");
}
}
}
You have to use AND here. The modified query:
String QUERY="SELECT * FROM login WHERE EMAIL=? And PASS=?";
My Full Example is :-
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class GetUserDetailsUsingPS {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// read user entered data
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter email id:");
String id = scanner.nextLine();
System.out.println("User id=" + id);
System.out.println("Please enter password to get details:");
String pwd = scanner.nextLine();
System.out.println("User password=" + pwd);
printUserData(id, pwd);
}
private static void printUserData(String id, String pwd) throws ClassNotFoundException,
SQLException {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "select name, country, password from Users where email = ? and password = ?";
try {
con = DBConnection.getConnection();
ps = con.prepareStatement(query);
//set the parameter
ps.setString(1, id);
ps.setString(2, pwd);
rs = ps.executeQuery();
while (rs.next()) {
System.out.println("Name=" + rs.getString("name") + ",country="
+ rs.getString("country") + ",password="
+ rs.getString("password"));
}
} finally {
if (rs != null)
rs.close();
ps.close();
con.close();
}
}
}
I am working in command prompt this is my code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnf) {
System.out.println("Driver could not be loaded: " + cnf);
}
}
public static void main(String[] args)
{
String connectionUrl = "jdbc:mysql://localhost:3306/mysql";
String dbUser = "root";
String dbPwd = "admin";
Connection conn;
ResultSet rs;
String queryString = "SELECT ID, NAME FROM exptable";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement stmt = conn.createStatement();
// INSERT A RECORD
stmt.executeUpdate("INSERT INTO exptable (name) VALUES (\"TINU K\")");
// SELECT ALL RECORDS FROM EXPTABLE
rs = stmt.executeQuery(queryString);
System.out.println("ID \tNAME");
System.out.println("============");
while (rs.next()) {
System.out.print(rs.getInt("id") + ".\t" + rs.getString("name"));
System.out.println();
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}
i am getting error like
java.lang.ClassNotFoundException and java.sql.SQLException
so may i know what mistake have i made
You might have missed the classpath in your java command. While executing from command prompt you must mention the class path along with your command.
java -cp
ex:
java -cp /home/test/jars:/home/test/src com.test.Lab
Values inserted using program are not seen in database. the following is the code which I used for the same
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con.prepareStatement("insert into user valiues(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
//I think I need to commit over here and I have tried the same but even with that I didn't see my inserted data in database
}
}
You've wrong query in your PreparedStatement
PreparedStatement stmt = con.prepareStatement("insert into user (id, name) values(?,?)");
You query is wrong and you are never executing it.
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
stmt.execute();
Maybe you can use try..catch help you to find the mistake you make just a wrong word
You are not executing your query inside preparedStatement. Also make sure you have valid SQL.
You can use PreparedStatement.executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
Try
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
stmt.executeUpdate();
From maintenance point of view, we specify order of columns in insert query like.
insert into user (id, name) values(?,?)
Commit:
You can check your database configuration about autoCommit. If by default autoCommit is true then you can omit commiting in your code else you will have to commit it manually in your code. Like
con.commit();
Connection close:
You should close your statements and connection when they are no longer required.
stmt.close();
connection.close();
Note: Don't forget to handle/throw Exceptions throws from all these methods such as SQLException.
public static void main(String args[]) {
String dbURL = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "root";
try {
Connection conn = DriverManager.getConnection(dbURL, username, password);
if (conn != null) {
System.out.println("Connected");
}
String sql = "INSERT INTO Users (id, password,) VALUES (?, ?)";
PreparedStatement statement;
statement = conn.prepareStatement(sql);
statement.setInt(1, 1);
statement.setString(2, "admin");
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A Record inserted successfully!");
}
} catch (SQLException e) {
System.out.println("Exception occured" + e);
}
}
After setting value need PreparedStatement executed
Look at below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con
.prepareStatement("insert into user valiues(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
stmt.execute();//You have to execute this statement
// I think I need to commit over here and I have tried the same but even
// with that I didn't see my inserted data in database
}
}
This works:
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
stmt.executeUpdate();
}
}
Hi I a have MySql installed with Netbeans and have been trying to use Java with MySQL, however I am running into an issue when I run it. My database is called "test" and my table is "task". The two columns I have are: "id", and "task" (and I realized that naming a variable the same as the table probably is not a good idea). I also have a side question in the code area asking what it does. This is the error:
run:
May 22, 2015 11:52:25 PM databasetest.DatabaseTest main
SEVERE: Operation not allowed after ResultSet closed
java.sql.SQLException: Operation not allowed after ResultSet closed
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.ResultSetImpl.checkClosed(ResultSetImpl.java:804)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6986)
at databasetest.DatabaseTest.main(DatabaseTest.java:43)
BUILD SUCCESSFUL (total time: 41 seconds)
This is my code:
package databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DatabaseTest {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement pst = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "cinder";
try {
String author = "Trygve Gulbranssen";
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
//^^ what is VERSION? What is this supposed to be doing?
for (int i=1; i<=1000; i++) {
String query;
query = "INSERT INTO task(task) VALUES(" + 2*i + ")";
st.executeUpdate(query);
}
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseTest.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseTest.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
SELECT VERSION() is meant to tell you your MySQL version. First, print the result of the SELECT then run your other queries. Running intermediate insert queries with the Statement implicitly closes the ResultSet, hence your error. Move
if (rs.next()) {
System.out.println(rs.getString(1));
}
before you run
for (int i=1; i<=1000; i++) {
// String query;
String query = "INSERT INTO task(task) VALUES(" + 2*i + ")";
st.executeUpdate(query);
}
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