when i run the file, it accepts the query and says update success but when i check my database why does it not update?
private void btnUpdateDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(radioUpdate.isSelected()){
try{
Class.forName("com.mysql.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/soften?zeroDateTimeBehavior=convertToNull","root","");
st=cn.createStatement();
String sql="UPDATE `tblproductssales` SET "
+" product = ?,quantity = ?"
+" WHERE 'sale no' = ?";
PreparedStatement pst = cn.prepareStatement(sql);
pst.setString(1,editProduct.getText());
pst.setString(2,editQty.getText());
pst.setString(3,editSaleID.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"success update");
//**when i run the file this JOPtionpPane shows
}catch(Exception e){e.printStackTrace();}
}
}
here is my database, the table name is tblproductssales
Related
I am trying to run below code on netbeans but it is throwing this error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, esalary=?, eage=?, egender=?, edept=? where eid = ?' at line 1".
please help me with the error
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
//open connection
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false","root","BakerStreet#221b");
//mysql query to update
String sql = "update emp set ename=?, esalary=?, eage=?, egender=?, edept=? where eid = ?";
PreparedStatement ptsmt = con.prepareStatement(sql);
ptsmt.executeUpdate(sql);
ptsmt.setString(1,empName.getText());
ptsmt.setInt(2,Integer.parseInt(empSal.getText()));
ptsmt.setInt(3,Integer.parseInt(empAge.getText()));
ptsmt.setString(4,empGen.getText());
ptsmt.setString(5,empDep.getText());
ptsmt.setInt(6,Integer.parseInt(id.getText()));
ptsmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Record updated Successfully");
con.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
you have called twice executeUpdate(sql) so remove one
you have called executeUpdate(sql) before adding value to parameters so do this :
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
//open connection
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false","root","BakerStreet#221b");
//mysql query to update
String sql = "update emp set ename=?, esalary=?, eage=?, egender=?, edept=? where eid = ?";
PreparedStatement ptsmt = con.prepareStatement(sql);
ptsmt.setString(1,empName.getText());
ptsmt.setInt(2,Integer.parseInt(empSal.getText()));
ptsmt.setInt(3,Integer.parseInt(empAge.getText()));
ptsmt.setString(4,empGen.getText());
ptsmt.setString(5,empDep.getText());
ptsmt.setInt(6,Integer.parseInt(id.getText()));
//execute update ...
ptsmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Record updated Successfully");
con.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
I have downloaded aws sdk and connected my account and the database. But now I do not know what I need to do next. How do insert, delete or create table through java on eclipse.
I know to do these in a local database. I tried changing the url in getConnection() function to the my endpoint on eclipse but I keep getting error stating
"Access denied for user 'aws'#'xxx.xxx.xxx.xxx' (using password: YES)" (real IP modified for security reasons).
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.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private static final String url = "jdbc:mysql://aws.cyduxshnlizb.ap-south-1.rds.amazonaws.com:3306";
final private String user = "myusername";
final private String passwd = "mypassword";
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection(url,user,passwd);
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from feedback.comments");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into feedback.comments values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from feedback.comments");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from feedback.comments");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from feedback.comments where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from feedback.comments");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}
I'm develop an application to connect MySQL via JDBC. In an action, I need to execute two queries, sql to read, and sql to update.
To make sure, sql to read query would be executed first, and sql to update to be executed later, I use JDBC transaction. But somehow, the problem is, mysql execute 2nd query first, and then the first read query.
Looking for suggestions. Many thanks.
// Sql connection
Connection conn = null;
Statement stmt = null;
PreparedStatement preparedStatement = null;
PreparedStatement preparedStatementUpdate = null;
String sql = "SELECT item_name, item_detail FROM Order_Printing where kitchen_id = ? and order_printed = ?";
String sqlFlag = "UPDATE order_printing set order_printed = 1 where kitchen_id = ?";
try {
// Register JDBC driver (Note to add mysql connector jar file)
Class.forName("com.mysql.jdbc.Driver");
// Step 3: open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
conn.setAutoCommit(false); // Disable auto-commit mode
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, 4);
preparedStatement.setInt(2, 0);
ResultSet rs = preparedStatement.executeQuery();
//
preparedStatementUpdate = conn.prepareStatement(sqlFlag);
preparedStatementUpdate.setInt(1, 4);
preparedStatementUpdate.executeUpdate();
int startingPos = 10;
int orderNumber = 1;
while (rs.next()) {
String item_name = "Order " + orderNumber++ + ": ";
item_name += rs.getString("item_name");
String item_detail = rs.getString("item_detail");
startingPos += 20;
g.drawString(item_name, 0, startingPos);
startingPos += 20;
g.drawString(item_detail, 0, startingPos);
}
conn.commit();
} catch (SQLException se) {
se.printStackTrace();
} catch (ClassNotFoundException se) {
se.printStackTrace();
} catch (Exception se) {
se.printStackTrace();
} finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
Try executing rs.next() while loop BEFORE you call preparedStatementUpdate.executeUpdate();
From groovy script in SoapUI I need to connect to a mysql database to perform some queries. The problem is that due to security reasons no external access is possible.
Therefore it is required to get an ssh access (like a tunnel) and invoke mysql locally.
Initially I was reading the below project properties and then connect to mysql:
ServerUrl=jdbc:mysql://10.255.255.122:3306/db
ServerDbUser=user
ServerDbPwd=password
ServerDriver=com.mysql.jdbc.Driver
def url=testRunner.testCase.testSuite.project.getPropertyValue("ServerUrl")
def usr=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbUser")
def pwd=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbPwd")
def driver=testRunner.testCase.testSuite.project.getPropertyValue("ServerDriver")
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver(driver)
sqlServer = Sql.newInstance(url, usr, pwd, driver)`
But this didn't work so now it is required to establish first a ssh connection to the server with the IP 10.255.255.122 and then open the mysql connection locally. So I guess the Server Url will change to:
ServerUrl=jdbc:mysql://127.0.0.1:3306/db
But I don't know how to set first the ssh connection to the server.
Can someone help me with this?
Thanks.
Have a look at http://forum.soapui.org/viewtopic.php?t=15400 and connect to remote mysql database through ssh using java
It will give you an idea about implementing it in soapUI.
Below is the code by Ripon Al Wasim which is available as an answer at the stackoverflow link mentioned above
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
I am trying to make a Social network site where a user can log or register. Once logged in with correct credentials, the user could search in a friends list and invite him/her to be friend.
So far I have made 2 jsp files-
1 index.jsp [2] UserRegistration.jsp
[2]mySQl has SocialNetwork Schema with UserInfo and userRegistration tables.
[3] and in src folder my RegistrationServlet is like this:
// ********************************************************************
// JDBC driver name and database URL
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/SocialNetwork";
// ***********************************************************************
// Database credentials
final String USER = "root";
final String PASS = "root";
Connection conn = null;
Statement stmt = null;
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// connection to mySQL server and Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
// create a Statement object ()
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
// Execute a query
String sql = "INSERT INTO SocialNetwork.userInfo"
+ "(userName, userPW)" + "VALUES('" + nUser + "','" + nPW
+ "')";
int i = stmt.executeUpdate(sql);
out.println("Connection successfull.." + i);
//Update the Db
stmt.executeUpdate(sql);
// executeQuery () method and save it on ResultSet
sql = "SELECT * FROM SocialNetwork.userInfo";
ResultSet rs = stmt.executeQuery(sql);
// check inserted rows in the Db table
while (rs.next()) {
String Db_Name = rs.getString("userName");
String passwordFromDb = rs.getString("userPW");
// rs.getString(newPassW)
out.println("<br>DbName **" + Db_Name);
out.println("->DbPass **" + passwordFromDb);
}
} catch (Exception e) {
e.printStackTrace();
}
How could I connect the UserLogin servlet to the UserInfo table so that if the user’s name and password are found and matched in the DB , he could see his/her friends’ list.
If that username and password is not found in the UserInfo, a message should display that the user has to Register first.
Once the user is logged-in, he should see a list of all the Usernames and Age.
Later, the user could select a user from that list and invite that user to be his/her friend.