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();
}
}
Related
I am new to JDBC and using a tutorial to create my first connection. However, I am getting the below error -
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
import java.sql.*;
public class Demo {
public static void main(String[] args) throws Exception {
String url="jdbc:mysql://localhost:3306//demo";
String user="root";
String password="vishal123";
String query = "select * from student";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("user_name");
System.out.println(name);
st.close();
con.close();
}
}
Do let me know if you need any more details to solve the problem.
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();
}
}
}
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:
I'm trying to run a query against a Sybase database. It seems like the connection is made successfully but when it hits rs.next() it fails to go to the first row in the results. It jumps down to the rs.Close().
I know for a fact that my query below works. I'm running it in a sql tool and it returns one record.
Please can someone tell me what I'm doing wrong?
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import com.sybase.jdbc4.jdbc.SybDataSource;
import com.sybase.jdbc4.jdbc.SybDriver;
public class test {
public static void main(String[] args) throws SQLException {
SybDriver sybDriver = null;
Connection conn = null;
Statement stmt = null;
String host = "123.12.34.56";
String url = "jdbc:sybase:Tds:"+host+":1300";
String username = "testuser";
String password ="password";
try{
sybDriver=(SybDriver)Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select top 1 brand, model,color,serialnum from myTable order by newid()");
while(rs.next())
{
String one = rs.getString(1);
String two = rs.getString(2);
String three = rs.getString(3);
String four = rs.getString(4);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
}
}
I have installed MYSQLSERVER 5.1.Then I installed mysql-connector-java-3.0.8-stable-bin.jar and put in drive c with folder core that is C:\core.Then in properties of computer I create user variable with variable name CLASSPATH and variable value:C:\core\mysql-connector-java-3.0.8-stable-bin.jar.
Now I have created database EMPLOYEE4
My java code is:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
class MySQLTest{
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query ="select count(*) from EMPLOYEE4 ";
Connection dbCon = null;
Statement stmt = null;
ResultSet rs = null;
//getting PreparedStatment to execute query
stmt = dbCon.prepareStatement(query);
//Resultset returned by query
rs = stmt.executeQuery(query);
while(rs.next()){
int count = rs.getInt(1);
System.out.println("count of stock : " + count);
}
} catch (Exception ex) {
ex.printStackTrace();
//Logger.getLogger(CollectionTest.class.getName()).log(Level.SEVERE, null, ex);
} finally{
//close connection ,stmt and resultset here
}
}
}
I get error that java.sql.SQLEXCEPTION:communication link failure:java.IO.Exception underlying cause:Unexpected end of input stream
You should be getting NPE. As you are executing your query on dbCon and not on dbcon
// initialize here
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query ="select count(*) from EMPLOYEE4 ";
// Null here
Connection dbCon = null;
// on dbCon which is null
stmt = dbCon.prepareStatement(query);
EDIT
This how your code suppose to look like.
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query = "select count(*) from EMPLOYEE4 ";
Statement stmt = dbcon.createStatement();
ResultSet rs = stmt.executeQuery(query);