I'm writing a small program with a mysql connection. I have to insert data into the database. The connection is ok but when I try to execute a query it doesn't work. all statements after executeQuery() statement doesn't work.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection connect=null;
PreparedStatement preparedStatement;
String JDBC_DRIVER="com.mysql.jdbc.Driver";
String DB_URL="jdbc:mysql//localhost/jarvis";
String USER = "test";
String PASS = "test";
try{
Class.forName(JDBC_DRIVER);
connect = DriverManager.getConnection(DB_URL, USER, PASS);
}
catch(ClassNotFoundException e){
out.println("Errore: "+e);
} catch (SQLException ex) {
Logger.getLogger(Prova.class.getName()).log(Level.SEVERE, null, ex);
}
out.println();
out.println("qui");
String query = "INSERT INTO users(Nome, Cognome, Username, Password) values(?, ?, ?, ?)";
try (PreparedStatement insert = connect.prepareStatement(query)) {
insert.setString(1, "name");
insert.setString(2, "sur");
insert.setString(3, "gvhgv");
insert.setString(4, "qfwe");
insert.executeUpdate();
}
catch(Exception e){
out.println("Errore "+e);
}
out.println("Fine");
}
on executeQuery it stop working and doesn't insert the values into the database.
P.S.: sorry for my English
foto
Firstly your JDBC Connection URL is wrong, it should be this
String DB_URL = jdbc:mysql://localhost/jarvis
instead of this:
String DB_URL = jdbc:mysql//localhost/jarvis
You can follow the MySQL documentation whenever you are in doubt about anything.
Please note that mentioning port is not necessary if it is skipped it would default to MySQL's default port 3306.
Secondly, use executeUpdate() method instead of executeQuery method. It is best suggested to test your code in chunks, like DB Connection is successful, able to retrieve data from the underlying DB and then inserting into the DB.
Or even a better way is to debug your code and at least provide where you find the NullPointerException as you say you're getting now!
Edit:
You must have your JDBC Connector/J jar available for your code to access it if you use an IDE (then in its build path) and in the CLASSPATH global variable (for references when we don't use an IDE). It is better to have it on your CLASSPATH if you are not going to change these dependencies any often.
Hope this helps!
Related
I am developing a Website with a Registration page. I want to store the user details in the table of the MySQL database on Google App Engine. Following is the JDBC connection URL:-
Connection con = DriverManager.getConnection("jdbc:mysql://google/my_database_name?cloudSqlInstance=my_db_instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=My_Username&password=My_Password&useSSL=false", "root", "My_Password");
But this URL isn't working as even after registering, no details are stored in the table of my database. So, do suggest any alternatives. Thank you
The following is the RegistrationServlet code which takes input values from Register.jsp and I want it to store the values into my gcloud db table:-
#WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1 L;
public RegistrationServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String first_name = request.getParameter("f1");
String last_name = request.getParameter("l1");
String phone = request.getParameter("p1");
String email = request.getParameter("e1");
String uname = request.getParameter("uname");
String user_dob = request.getParameter("udate");
String password = request.getParameter("pwd");
UserData ud = new UserData();
ud.setFirst_name(first_name);
ud.setLast_name(last_name);
ud.setUname(uname);
ud.setPhone(phone);
ud.setEmail(email);
ud.setUser_dob(user_dob);
ud.setPassword(password);
// validate given input
if (first_name.isEmpty() || last_name.isEmpty() || phone.isEmpty() || email.isEmpty() || password.isEmpty()) {
RequestDispatcher rd = request.getRequestDispatcher("Register.jsp");
out.println("<font color=red>Please fill all the fields</font>");
rd.include(request, response);
} else {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// loads mysql driver
try {
Connection con = DriverManager.getConnection("jdbc:mysql://google/my_database_name?cloudSqlInstance=my_db_instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=My_Username&password=My_Password&useSSL=false", "root", "My_Password");
String query = "insert into users values(?,?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(query); //generates sql query
ps.setString(1, first_name);
ps.setString(2, last_name);
ps.setString(3, uname);
ps.setString(4, phone);
ps.setString(5, email);
ps.setString(6, user_dob);
ps.setString(7, password);
ps.executeUpdate();
System.out.println("successfully inserted");
ps.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpSession session = request.getSession();
session.setAttribute("username", first_name);
response.sendRedirect("Success.jsp");
}
}
I've followed the GCP CloudSQL for MySQL connection example and it has worked after deployment. I'll go step by step of the process I did so you can compare and see if there's some configuration step missing on your end.
Used a MySQL 2nd Gen Cloud SQL instance. This instance is in the same project as the Google App Engine I'll deploy the script in
Created a new database in the CloudSQL instance
Ran the command gcloud sql instances describe instance1 to get the instance connection name in the form of <MY-PROJECT>:<REGION>:<INSTANCE-NAME>
Downloaded the GCP Java code samples and got to the Java 8 App Engine standard Cloud SQL example:
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
cd java-docs-samples/appengine-java8/cloudsql/
Completed the fields <INSTANCE_CONNECTION_NAME>, <user>, <password> and <database> from the POM file with the connection values for my case. This fields will be used by the appengine-web.xml to create the cloudsql property that will be used as the connection URL by the code in CloudSqlServlet.java
Also in the appengine-web.xml, I changed the <service> name to default. There's actually no need to change anything on this file but I chose to change the service due to personal preference
The other required dependencies where already in the downloaded POM
Deployed to GAE with mvn appengine:deploy
This is a minimal example of a working GAE to Cloud SQL connection for MySQL. Try to follow this steps to test if the connection works poperly with the provided code example.
I am trying to insert data into a database using java servlets and an mvc. I have a class called CheckoutDb that uses connection pool and prepared statements to insert data.
public class CheckoutDb {
public static int insert(Checkout checkout) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query
= "INSERT INTO Checkout (FirstName, LastName, EmailAddress, "
+ "BookTitle, DueDate) "
+ "VALUES (?, ?, ?, ?, ?)";
try {
ps = connection.prepareStatement(query);
ps.setString(1, checkout.getFirstName());
ps.setString(2, checkout.getLastName());
ps.setString(3, checkout.getEmailAddress());
ps.setString(4, checkout.getBookTitle());
ps.setString(5, checkout.getFormattedDate());
return ps.executeUpdate();
} catch (SQLException e) {
System.out.println(e);
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
The problem I seem to be having is actually inserting the data from the controller class. I have tried gettting the request params from the form and then storing them to the object and then calling the insert method from the CheckoutDb class, but it will not insert any data to the table. Any help would be greatly appreciated. If more code is needed to display, I will provide if needed. Thanks.
private String doCheckout(HttpServletRequest request,
HttpServletResponse response) {
String firstName= request.getParameter("first_name");
String lastName= request.getParameter("last_name");
String emailAddress= request.getParameter("email_address");
String bookTitle= request.getParameter("book_title");
Checkout checkout=new Checkout();
Date date= checkout.getDueDate();
//TODO: Implement code to check out the book here.
checkout=new Checkout(firstName,lastName,emailAddress,bookTitle,date);
CheckoutDb.insert(checkout);
return "/thankyou.jsp";
}
Solution:
After issuing ps.executeUpdate(), you need to issue connection.commit(). That will make the changes permanent to the database and you will be able to see the changes in the database using another connection. JDBC tutorial (http://docs.oracle.com/javase/tutorial/jdbc/TOC.html) can give you details on how to manage transactions using commit/rollback.
Below is my Java program. I am calling a PLSQL procedure to update the Employee name. I turned off the commit in the PLSQL code so that I can do the commit and rollback from Java code. But even after I turned off the auto commit and doing explicit rollback, still the details are updated in the table.
How? I have no idea, please help.
Here's my Java code. In PLSQL, it just read the value and does an update statement . No commits.
public class TestCommit {
public static void main(String[] args) throws SQLException, IOException {
CallableStatement callableStatement = null;
Connection conn = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager
.getConnection("jdbc:oracle:thin:testuser/testpwd#//testdb:1521/testbx");
conn.setAutoCommit(false);
String sql = "{call testpkg.saveemployee(?,?)}";
callableStatement = conn.prepareCall(sql);
callableStatement.setString("name", "spider");
callableStatement.setString("id", "A101");
callableStatement.executeQuery();
conn.rollback();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// Close the statement
callableStatement.close();
// Close the connection
conn.close();
}
}
}
edit: PLSQL
CREATE OR REPLACE PROCEDURE saveemployee(
name IN employee.ename%TYPE,
id IN employee.eid%TYPE)
IS
BEGIN
UPDATE employee SET ename = name WHERE eid = id;
END;
My bad, I was calling a wrong procedure, there were two versions of the same procedure in two different packages,
one has the commit , the other one doesn't have the commit. I was calling the one that had the commit.
Now that the commit is removed from both procedures, my code seems to work now.
I have a requirement to insert clob data in SQLServer Table.
below Code is throwing java.lang.AbstractMethodError: net.sourceforge.jtds.jdbc.ConnectionJDBC3.createClob()Ljava/sql/Clob
public void executeQueryWithPreparedStatements(int messageID,String xmlMessage,String xmlDataStorageType) throws SQLException {
String dataTypeSpecificSQL = "Insert into OXI_MESSAGE_AS_CLOB(messageid,MSG_content) values (?,?)";
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(dataTypeSpecificSQL);
statement.setInt(1, messageID);
Clob clobData = connection.createClob();
clobData.setString(0,xmlMessage);
statement.setClob(2, clobData);
statement.executeUpdate();
}catch(SQLException sqle){
throw sqle;
}finally {
releaseResource(statement);
}
}
I am using Jtds-1.2.8.jar
When I checked the sourcecode I have found that createClob() method is not available in net.sourceforge.jtds.jdbc.ConnectionJDBC3 class
Whether someOne else also faced this issue ?
Please provide suggestion for how to insert clob data with Jtds Driver in SQLServer with this issue?
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath