Servlet connection to database - java

I am trying to connect to jdbc database from servlet.I have separate class dbconnect for connection and inserting data to database.
Here is my dbconnect class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class dbconnect {
Connection conn;
Statement stm;
dbconnect(){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection
("jdbc:derby://localhost:1527/type","nika",
"mypass");
stm = conn.createStatement();
System.out.println("success");
String sql = "INSERT INTO USERS " + "VALUES (\"tsogiaidze#yahoo.com\", \"nika\", \"nika\", \"kaci\")";
stm.executeUpdate(sql);
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
In servlet I create new dbconnect object which must insert data to database,but it does not happen.
Can anyone tell me why it does not work?
I guess I make fundamental mistake.
Thank you.
For more details I have jsp file which sends html form data to this servlet and then I try to write these data to database using dbconnect class.
I have changed dbconnect class like this,now I use preparedstatement to write files but still does not work.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class dbconnect {
Connection conn;
Statement stm;
dbconnect(){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/type","nika","nika");
stm = conn.createStatement();
System.out.println("success");
String sql = "INSERT INTO NIKA.USERS (mail, pass, gender, saxeli) VALUES (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "tsogiaidze");
statement.setString(2, "nika");
statement.setString(2, "nika");
statement.setString(2, "kaci");
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}

Use single quote to surround your texts.
String sql = "INSERT INTO USERS VALUES ("
+ "'tsogiaidze#yahoo.com', 'nika', 'nika', 'kaci')";
Or better, use a PreparedStatement:
String sql = "INSERT INTO USERS VALUES (?, ?, ?, ?)");
PreparedStatement stm = conn.prepareStatement(sql);
System.out.println("success");
stm.setString(1, "tsogiaidze#yahoo.com");
stm.setString(2, "nika");
stm.setString(3, "nika");
stm.setString(4, "kaci");
stm.executeUpdate();

Your insert statement is possibly wrong try this
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("making connection");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "welcome");
PreparedStatement stmt=conn.prepareStatement("INSERT INTO student(student_name,student_id,class) VALUES(?,?,?)");
stmt.setString(1, "abc");
stmt.setString(2, "4");
stmt.setString(3, "ukg");
stmt.executeUpdate();
System.out.println("query executed");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
Please change the driverclass and connectionString

in my case I used PostgreSQL with maven
add in pom.xml the following code
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.3.2</version>
</dependency>
in servlet class
Class.forName("org.postgresql.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + DB_NAME, USER, PASS);

Related

Howo can I connect to database with Java

I'm new to Java and I want to connect with MySQL local server, but it's throwing an exception error. How can I fix the code?
Connection information:
Lport:3306
database name= siba_1
table name= test_1
Code:
package java_recap;
import java.sql.*;
public class Java_recap {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mqsql://localhost:3306/siba_1","root","");
Statement stn=con.createStatement();
ResultSet rs=stn.executeQuery("select * from test_1");
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}
catch(Exception e){
System.out.println("e");
}
}
}
DriverManager is a old way of doing things. if you still want to use DriverManger then:
Need mysql dependency add jar on classpath or use maven like below :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
Now Let's see how we can connect to our database and execute a simple select-all through a try-with-multiple-resources:
String sql = "select * from test_1";
String connectionUrl = "jdbc:mysql://localhost:3306/siba_1?
serverTimezone=UTC";
try (Connection conn = DriverManager.getConnection(connectionUrl,
"root", "");
PreparedStatement ps =
conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2));
// do something with the extracted data...
}
} catch (SQLException e) {
// handle the exception
}
Other way : The better way is to get a DataSource either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/siba_1");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("root");
dataSource.setPassword("");
dataSource.setServerName("localhost");
and then get connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from test_1");
...
rs.close();
stmt.close();
conn.close();

Not able to insert million records from csv file to MySql database

So I wanted to read per say 100 lines and print it and it should be happening for every 100 lines and I don't know where to insert that code. The CSV file with one million records isn't getting inserted into the DB as only few thousand are getting inserted.
String csvFilePath = "C:\\Student1.csv";
try {
BufferedReader lineReader = new BufferedReader(new FileReader("C:\\File12\\Student1.csv"));
CSVParser records = CSVParser.parse(lineReader, CSVFormat.EXCEL.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
System.out.println(records.size);
ArrayList<TestSql> students = new ArrayList<TestSql>();
for (CSVRecord record : records) {
TestSql testsql = new TestSql();
testsql.setDate(record.get(0));
testsql.setName(record.get(1));
testsql.setGender(record.get(2));
students.add(testsql);
}
PreparedStatement statement = null;
Connection con = dbconnection();
String sql = "INSERT INTO test12(DOB, NAME, GENDER) VALUES (?, ?, ?)";
statement = con.prepareStatement(sql);
for (TestSql record : students) {
statement.setString(1, record.getDate());
statement.setString(2, record.getName());
statement.setString(3, record.getGender());
statement.addBatch();
}
statement.executeBatch();
con.commit();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
public static Connection dbconnection() {
Connection connection = null;
try {
System.out.println( "Hello World!" );
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/newschema1", "root", "12345");
System.out.println("connection sucessfull");
connection.setAutoCommit(false);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
If you want to insert records from the CSV file into the database table in batches of 100, then you need a counter. In the below code I use a variable count. Whenever it reaches 100, the code inserts those 100 rows and resets the count variable.
Note: More explanations after the code.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class CsvParse {
private static final int LIMIT = 100;
public static Connection dbConnection() throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/newschema1",
"root",
"12345");
connection.setAutoCommit(false);
return connection;
}
public static void main(String[] args) {
try (BufferedReader lineReader = new BufferedReader(new FileReader("C:\\File12\\Student1.csv"))) {
CSVParser records = CSVParser.parse(lineReader,
CSVFormat.EXCEL.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
String sql = "INSERT INTO test12(DOB, NAME, GENDER) VALUES (?, ?, ?)";
Connection con = dbConnection();
PreparedStatement statement = con.prepareStatement(sql);
int count = 0;
for (CSVRecord record : records) {
count++;
if (count > LIMIT) {
count = 1;
statement.executeBatch();
con.commit();
statement.clearBatch();
}
statement.setString(1, record.get(0));
statement.setString(2, record.get(1));
statement.setString(3, record.get(2));
statement.addBatch();
}
// Insert last batch that may be less than LIMIT.
statement.executeBatch();
con.commit();
con.close();
records.close();
}
catch (IOException | SQLException e) {
e.printStackTrace();
}
}
}
In method dbConnection(), I removed Class.forName() since it is no longer needed. I also changed the exception handling. If the method fails to obtain a database connection then there's not much point in continuing since you won't be able to insert anything into the database and that's the whole point of the program. So catching the SQLException in method dbConnection() and printing the stack trace means that when you try to create a PreparedStatement, you will get a NullPointerExcetion since con will be null.
In method main I use try-with-resources when creating lineReader.
I don't see the reason for class TestSql. You can simply set the PreparedStatement parameters directly from the CSV record.
Since Java 7 there is multi-catch so no need for a separate catch block for each exception when each catch block simply prints the stack trace.

JDBC Update query error

I can't execute the update query on JDBC with where clause. I want to execute the query by concatenating some variables.
protected void updateEmail(String Email, String Username) {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "");
String query = "update access set email=" + Email + " where username=" + Username;
Statement st = conn.createStatement();
st.executeUpdate(query);
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
It says:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'bhusal1' in 'where clause'
String should be between two quotes 'name' instead of your way you have to use PreparedStatement instead to avoid syntax error or SQL Injection :
String query = "update access set email=? where username=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, email);
ps.setString(2, name);
ps.executeUpdate();
This is most likely a problem with concatenation of the request. The approach you use is extremely bad and can cause any problems (including security).
To avoid problems, use PrepareStatement when you need to submit sql query parameters.
Here's an example that should solve your problem:
void updateEmail(String email,String username) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "")) {
String query = "update access set email = ? where username = ?";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, email);
statement.setString(2, username);
statement.executeUpdate();
}
}
catch (SQLException e) {
System.out.println(e);
}
}
You should put your variables email and username between quotes in the where clause to be able to do the update query

JAVA: executing Catch not try

private void rtrBtnActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) depTbl.getModel();
try{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test1","admin","root");
Statement stmt = con.createStatement();
String query = "SELECT * FROM dept;";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String dno = rs.getString("deptno");
String dName = rs.getString("dname");
String lc = rs.getString("loc");
model.addRow(new Object[] {dno,dName,lc});
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Error In Connectivity");
}
}
Im trying to connect my JForm to the mysql database but not able to connect to the database, continuously executing catch statement "Error in Connectivity", please help how should i resolve this issue..............................................................................
Change the following line
Class.forName("java.sql.Driver");
to
Class.forName("com.mysql.jdbc.Driver");
in your code
This line of code is not correct - Class.forName("java.sql.Driver");
The java.sql.Driver is an interface. You need to provide the correct jdbc driver class for you appropriate db.
Such as for Oracle - Class.forName("oracle.jdbc.driver.OracleDriver");

Netbeans ucanaccess [duplicate]

This question already has an answer here:
invalid datetime format: insert date/time into Access from Java
(1 answer)
Closed 6 years ago.
conn = Connect.ConnectDB();
String sql = "insert into Ianouarios ("
+"id,"
+"Hmerominia,"
+"Agores,"
+"Pliromes,"
+"Eksoda,"
+ "Zhta,"
+"Metaforika,"
+"Pliromimetafo,"
+"Epitages,"
+"Xondriki,"
+"Noiki,"
+"Plirominoiki)"
+ "values("+a1.getText()+ ",'"+a2.getText()+"','"+a3.getText()+"','"+a4.getText()+"','"+a5.getText()+"','"+a6.getText()+"','"+a7.getText()+"','"+a8.getText()+"','"+a9.getText()+"','"+ a10.getText()+ "','"+a11.getText()+"','"+a12.getText()+"')" ;
try{
pst = conn.prepareStatement(sql);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Saved");
//UpdateJTable();
//conn.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
I have an ms access database and i am updating it with the jdbc-odbc driver.
Can anyone show me how to do the same to work with ucanaccess driver?
I tried their ucanaccess page examples but no luck.
Update: I did this:
conn = Connect.ConnectDB();
try{
String sql = "INSERT INTO Synola(id,Hmerominia,Agores,Pliromes,Eksoda,Zhta,Metaforika,Pliromimetafo,Epitages,Xondriki,Noiki,Plirominoiki) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)" ;
/* SimpleDateFormat ddmmyyyyFormat = new SimpleDateFormat("dd/MM/yyyy");
Timestamp ddmmyyyy = new Timestamp(ddmmyyyyFormat.parse(a2.getText()).getTime()); */
// String s=ddmmyyyy.toString();
pst = conn.prepareStatement(sql);
pst.setString(1, a1.getText());
pst.setString(2,a2.getText());
pst.setString(3, a3.getText());
pst.setString(4, a4.getText());
pst.setString(5, a5.getText());
pst.setString(6, a6.getText());
pst.setString(7, a7.getText());
pst.setString(8, a8.getText());
pst.setString(9, a9.getText());
pst.setString(10, a10.getText());
pst.setString(11, a11.getText());
pst.setString(12, a12.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Saved");
//UpdateJTableSynola();
// conn.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
And now the problem is the date from the a2.getText() field which i put into database as (dd/MM/yyyy).The error is unparseable date.How can i fix this?
As JDBC-ODBC Bridge has been removed in JDK8, what you can do is to use JDBC along with UCanAccess API to connect to an MSAccess database.
connection = DriverManager
.getConnection("jdbc:ucanaccess:////REMOTE-IP-ADDRESS/shared-folder/TestDB.mdb");
System.out.println("CONNECTION ESTABLISHED....");
Here is a small example(tested in Java 8) which connects to a remote MS-Access DB using JDBC/UCanAccess API. Make sure you have the following jars in your project build path.
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.0.jar
ucanaccess-2.0.9.5.jar
Code:
/**
* Connects to a remote MS-Access DB using JDBC/UCanAccess API.
*/
package miscellaneous;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ConnectRemoteDB {
public static void main(String[] args) {
initializeConnection();
}
/**
* Initializes remote database connection and inserts a record and closes the connection.
*/
private static void initializeConnection() {
System.out.println("Attempting Database Connection...");
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager
.getConnection("jdbc:ucanaccess:////REMOTE-IP-ADDRESS/shared-folder/TestDB.mdb");
System.out.println("CONNECTION ESTABLISHED....");
String insertTableSQL = "INSERT INTO Table1" + "(Name) VALUES"
+ "(?)";
preparedStatement = connection.prepareStatement(insertTableSQL);
preparedStatement.setString(1, "Sandeep");
preparedStatement.executeUpdate();
System.out.println("RECORD INSERTED...");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
System.out.println("CONNECTION CLOSED...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Categories