inserting data through a servlet using JDBC - mysql

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.

Related

incompatible types: java.sql.Statement cannot be converted to java.beans.Statement

I am trying to make a ATM Project in Net beans but I am stack here.
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
Statement st = null;
if (accNumField.getText().isEmpty() || pinField.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please fill in the Fields");
}else{
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankmanagement", "root", "");
String query = "Select from * clients where AccNum='"+accNumField.getText()+"' and PIN="+pinField.getText()+"";
**st = con.createStatement();
rs= st.executeQuery(query); **
if(rs.next()){
new MainMenu().setVisible(true);
this.dispose();
}else{
}
} catch (Exception e) {
enter image description hereCan someone help me where is the problem in my code?
I am trying to get access in the database and authentication the user in my bank.
Thanks for your time

How do I work with aws rds myql on eclipse(Java)?

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) {
}
}
}

why is my database not updating? (using netbeans xampp mysql)

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

Database doesn't work on netbeans

My database does not work, I get and error that I pasted after the code:
try {
String url = "jdbc:derby:test";
String name = "root";
String password = "123";
Connection con = DriverManager.getConnection(url, name, password);
Statement state = con.createStatement();
String query = "INSERT INTO APP.UNTITLED (id , name , password ) VALUES (1, 'Anas','123456789')";
state.execute(query);
}
catch (SQLException e){
e.printStackTrace();
}
}
}
this is the error that appears:
java.sql.SQLException: No suitable driver found for jdbc:derby:test
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at testdatabase.TestDatabase.main(TestDatabase.java:25)
BUILD SUCCESSFUL (total time: 0 seconds)
You must use Class.forName to look for the classpath to find suitable driver.
try {
...
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Connection con = DriverManager.getConnection(url, name, password);
Statement state = con.createStatement();
...
}
catch (....
Don't forget to add library to your project
java DB Driver
with following jar files.
derby.jar
derbyclient.jar
derbynet.jar

set mysql connection behind ssh in groovy script SoapUI

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();
}
}
}