can't insert data to mysql - java

I can connect fine in Netbeans using this:
Connection conn = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarymangementsystem","root","root");
if(conn!= null)
{
System.out.println("connected");
}
}catch(Exception e)
{
System.out.println("not connected");
}
}
But when it comes to adding data to the columns, i just cant.
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarymangementsystem","root","root");
Statement stmt=conn.createStatement();
String Query = "INSERT into librarian_details(username, name, email, password) VALUES("+ uname +", "+ fname +", " + emails + ", " + psword +")";
stmt.executeUpdate(Query);
JOptionPane.showMessageDialog(null, "Success!");
}
Anyone knows the problem?
Updated Problem:
String Query = "insert into book_details(Book_Name, ISBN, Author, Category, >Quantity, BookShelfNo,Row,Column) VALUES('" +bookname + "','" + ISBN + "','" + >AuthorName + "','" + Category + "','" + Quantity + "','" + ?BookShelfNo +"', '" >+ Row + "', '" + Column + "')";
I cant seem to insert any data to Row and Column using this:
String Row = jTextField9.getText();
String Column = jTextField10.getText();
Row and Column Datatype is int.

I guess the username, name, email and password fields are of String type and Data type used while creating the columns username, name, email and password of librarian_details is Varchar .
If so, then you need to update your query string to the below code:
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES('"+ uname +"','"+ fname +"','" + emails + "','" + psword +"')";
If your input String has an apostrophe (') character then you need to add an extra apostrophe (') character as an escape sequence.
For Example:your password is abc'aa
String uname = "abc";
String fname = "xyz";
String emails = "abc#xyz.com";
String psword = "abc''aa";//extra apostrophe (') character added
String Query = "INSERT into librarian_details(username, name, email, password) VALUES('"+ uname+ "','"+ fname+ "','"+ emails+ "','"+ psword+ "')";
Note: Adding extra apostrophe (') to the existing (') character is different than a double quote.
Below code is for your updated query
String bookname ="abc";
String ISBN="qwerty123";
String AuthorName="user3213";
String Category="New";
String Quantity="1";
String BookShelfNo="5";
int Row=1;
int Column=5;
String Query = "insert into book_details(Book_Name, ISBN, Author, Category, Quantity, BookShelfNo,`Row`,`Column`) VALUES('" +bookname + "','" + ISBN + "','" + AuthorName + "','" + Category + "','" + Quantity + "','" + BookShelfNo +"', " + Row + ", " + Column + ")";
stmt.execute(Query);
Note: you are using reserved keywords of sql like Row and Column.
I guess your column names in DB are Book_Name, ISBN, Author, Category, Quantity, BookShelfNo, Row and Column.
Suggestion:
Using PreparedStatement will save your time for writing a query (no need to remember datatype of variable and columns.)
PreparedStatement uses query caching functionality.
Hence, execution is faster than simple statement.
Below code depicts the usage of prepared statement for your query.
//query parameters will be dynamically set
String Query = "INSERT INTO book_details VALUES (?,?,?,?,?,?,?,?)";
//create a Prepared statement using connection object.
PreparedStatement pstmt = con.prepareStatement(Query);
//assign the query parameter values
pstmt.setString(1, bookname);
pstmt.setString(2, ISBN);
pstmt.setString(3, AuthorName);
pstmt.setString(4, Category);
pstmt.setString(5, Quantity);
pstmt.setString(6, BookShelfNo);
pstmt.setInt(7, Row);
pstmt.setInt(8, Column);
//display query string generated by PreparedStatement.
System.out.println("Query: "+pstmt.toString());
//Display result; result=1 means success.
int result = pstmt.executeUpdate();
System.out.println("result: "+result);

Escape the text values or even better - use prepared statements.
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES('"+ uname +"', '"+ fname +"', '" + emails + "', '" + psword +"')";
Prepared statements:
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES(?, ?, ?, ?)";

Concatenating values into a query is unsafe, it opens you up to SQL injection. You need to use a prepared statement instead:
try (PreparedStatement pstmt = connection.prepareStatement(
"INSERT into librarian_details(username, name, email, password) "
+ "VALUES(?, ?, ?, ?)")) {
pstmt.setString(1, uname);
pstmt.setString(2, fname);
pstmt.setString(3, emails);
pstmt.setString(4, psword);
pstmt.executeUpdate();
}

Related

Why am I getting this error: E/ERROR: The executeQuery method must return a result set.?

I'm trying to connect my project with an SQL-Server database. But I always get this error E/ERROR: The executeQuery method must return a result set.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES ('" + informacao.getNomeCliente() + "', '" + informacao.getNome() + "', '" + informacao.getEmail() + "', '" + informacao.getSatisfacao() + "', '" + informacao.getNota() + "') ";
Statement stmt = conn.createStatement();
ResultSet rSet = stmt.executeQuery(sql); // error here
I tried to change stmt.executeQuery to stmt.executeUpdate, but it underlines it red, and says that the output is int, so it is incompatible.
Using PreparedStatement is much safer.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, informacao.getNomeCliente())
pstmt.setString(2, informacao.getNome())
pstmt.setString(3, informacao.getEmail())
pstmt.setString(4, informacao.getSatisfacao())
pstmt.setString(5, informacao.getNota())
int result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
I think you should use the executeQuery method while querying tables in the database (when you have the SELECT keyword). When you want to execute SQL statements (like INSERT, UPDATE and others) you should use execute method, as seen in here.
In your case you could try:
Boolean rSet = stmt.execute(sql);

unable to compare screen values with sql table value

I am trying to compare the screen values input against the value stored in DB. Currently i am trying this code:
cell = sheet.getRow(i).getCell(2);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com:3306/madisondb","madisonadmin","t4xuw94$");// + "databasename=madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com";
Statement st = con.createStatement();
ResultSet Rs = st.executeQuery("select name, zipcode, state, city, street from business_master where user_id =(\r\n" +
"select id\r\n" +
"from user_master\r\n" +
"where email = 'cell.getStringCellValue()') \r\n");
while (Rs.next()) {
// System.out.println(Rs.getString(1) + " " + Rs.getString(2) + " " + Rs.getString(3) + " "
// + Rs.getString(4) + " " + Rs.getString(5));
System.out.println(Rs.getString(0));
}
The screen is not showing any values.. and when i am trying to print System.out.println(Rs.getString(3)) outside of the loop it gives me an error
java.sql.SQLException: Illegal operation on empty result set.
You are trying to find all the rows where the email address is literally the text 'cell.getStringCellValue()' rather than the value returned by that method.
Whilst you code assemble your query string, that lays you open to SQL injection attacks. Use a prepared statement instead
PreparedStatement st = con.prepareStatement(
"select name, zipcode, state, city, street from business_master where user_id =(" +
"select id " +
"from user_master " +
"where email = ?)");
st.setString(1, cell.getStringCellValue());
ResultSet Rs = st.executeQuery();

Inserting user data from JSP into postgres database

I created a registered form of user information with JSP. I want to insert user data into a table with userinfo in postgre database after submitting form. But instead of adding data into this table, it gives me errors. Please help me!
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String user = request.getParameter("uname");
String pwd = request.getParameter("pass");
String pwd2 = request.getParameter("pass2");
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/UserInformation", "postgres", "123456789");
PreparedStatement st = con.prepareStatement("insert into userinfo(firstname, lastname, email, username, password) VALUES ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "'");
//ResultSet rs;
int i = st.executeUpdate();
if (i > 0) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
%>
The output is:
org.postgresql.util.PSQLException: ERROR: syntax error at end of input
Position: 142
(This is a comment, but i can't comment because don't have 50 points)
You must know, that scriptlets are a bad practice when you work with JSP. When code keep in mind the software development principles, like DRY (don't repeat yourself), SRP (single responsibility principle) and more. You have mixed your views with domain model, never do that. The only thing that you get when doing this is:
Poor scalability
Poor maintenance
Spaghetti code
So, you need to re-structure your application by adding some layers (controllers and model).
Create a access data abstract layer for communication with your data (eg., dao, repository).
Create a controller for yours views.
Use JSTL in your views to avoid scriptlets.
You have an sql syntax error remove the comma and single quotation(,') at the end of your insert query
int i = st.executeUpdate("insert into userinfo(firstname, lastname, email, username, password, city, province, country) VALUES ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "','" + city + "','" + province + "','" + country + "'");
In addition use PreparedStatement instead of Statement to avoid sql injection.

Why do I keep getting this cursed SQL*Plus invalid identifier error?

I keep getting a invalid identifier exception when I try to run the below script:
javax.servlet.ServletException: java.sql.SQLException: [Oracle][ODBC][Ora]ORA-00904: "CUSTID": invalid identifier
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:rreOracle","xxxxxx","xxxxxxxx");
stmt = conn.createStatement();
PreparedStatement preparedStatement;
//get parameters from the request
String custID=request.getParameter("cust_ID");
String saleID=request.getParameter("sale_ID");
String firstName=request.getParameter("first_Name");
String mInitial=request.getParameter("mI");
String lastName=request.getParameter("last_Name");
String streetName=request.getParameter("street");
String city=request.getParameter("city");
String state=request.getParameter("state");
String zipCode=request.getParameter("zip_Code");
String DOB=request.getParameter("DOB");
String agentID=request.getParameter("agent_ID");
String homePhone=request.getParameter("home_Phone");
String cellPhone=request.getParameter("cell_Phone");
String profession=request.getParameter("profession");
String employer=request.getParameter("employer");
String referrer=request.getParameter("referrer");
preparedStatement = conn.prepareStatement("UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=?, customer.first_Name=?, customer.mI=?, customer.last_Name=?, customer.street_Name=?, customer.city=?, customer.state=?, customer.zip_Code=?,customer. DOB=?, customer.agent_ID=?, customer.home_Phone=?, customer.cell_Phone=?, customer.profession=?, customer.employer=?, customer.referrer=?"
+ " WHERE customer.cust_ID=custID ") ;
preparedStatement.setInt(1, Integer.valueOf(custID));
preparedStatement.setInt(2, Integer.valueOf(saleID));
preparedStatement.setString(3, firstName);
preparedStatement.setString(4, mInitial);
preparedStatement.setString(5, lastName);
preparedStatement.setString(6, streetName);
preparedStatement.setString(7, city);
preparedStatement.setString(8, state);
preparedStatement.setString(9, zipCode);
preparedStatement.setString(10, DOB);
preparedStatement.setInt(11, Integer.valueOf(agentID));
preparedStatement.setString(12, homePhone);
preparedStatement.setString(13, cellPhone);
preparedStatement.setString(14, profession);
preparedStatement.setString(15, employer);
preparedStatement.setString(16, referrer);
preparedStatement.executeUpdate();
you can try
<%preparedStatement = conn.prepareStatement("UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=?, customer.first_Name=?, customer.mI=?, customer.last_Name=?, customer.street_Name=?, customer.city=?, customer.state=?, customer.zip_Code=?,customer. DOB=?, customer.agent_ID=?, customer.home_Phone=?, customer.cell_Phone=?, customer.profession=?, customer.employer=?, customer.referrer=?"
+ " WHERE customer.cust_ID=?") ;%>
<%preparedStatement.setString(17, custID );%>
or
<%preparedStatement = conn.prepareStatement("UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=?, customer.first_Name=?, customer.mI=?, customer.last_Name=?, customer.street_Name=?, customer.city=?, customer.state=?, customer.zip_Code=?,customer. DOB=?, customer.agent_ID=?, customer.home_Phone=?, customer.cell_Phone=?, customer.profession=?, customer.employer=?, customer.referrer=?"
+ " WHERE customer.cust_ID="+custID ) ;%>
Hope it helps.
In this part of your statement "WHERE customer.cust_ID=custID" oracle is looking for a value called "custID".
At that point,the variable names in your context aren't relevant - inside the SQL an "where A=B" statement refers to "column A == column B" - since there's not "custID" column in the table, oracle complains.

I need help on INSERT statements using JDBC

I need to use an INSERT statement, and 2 of the records in this statement are fields which are calculated in the program, and need to be added to the database.
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', PKmod, PKexpo)";
stmt.executeUpdate(sql);
'PKmod' and 'PKexpo' are BigInteger fields whose value is calculated in the java program, how can I add these values to the database?
Thanks for any help! :)
Please do not insert sqls this way. Use prepared statement. Change your sql to use "?" markers instead of concatenating values.
It depends on the DBMS. For mysql perhaps BIGINT should suffice?
http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
You need to concatenate the string!!!!
So do as follows:
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01',"+ PKmod+", "+PKexpo+")";
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', "
+ PKmod
+ ", "
+ PKexpo
+ ")";
stmt.executeUpdate(sql);
// First Check That PKmod & PKexpo values are not Zero Or Null.
System.out.println("Executing....");
String sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01'," + PKmod + "," + PKexpo +")";
PreparedStatement pStmt = null;
pStmt = con.prepareStatement(sql);
pStmt.executeUpdate();
closePreparedStatement(pStmt);

Categories

Resources