<%# page import= "java.sql.*"
import= "java.util.*"%>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
Statement st = con.createStatement();
String name = request.getParameter("name");
String username = request.getParameter("user");
String pass = request.getParameter("pas");
String cpass = request.getParameter("cpas");
String sql2 = "select * from user where user='"+username+"';";
ResultSet rs = st.executeQuery(sql2);
if(rs.next())
{
response.sendRedirect("index.html?err=Username already taken");
}
else
{
String sql = "insert into user values('"+name+"', '"+username+"','"+pass+"',"+cpass+");";
st.executeUpdate(sql);
response.sendRedirect("blank.html");
}
%>
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
Statement st = con.createStatement();
String name = request.getParameter("name");
String username = request.getParameter("user");
String pass = request.getParameter("pas");
String cpass = request.getParameter("cpas");
String sql2 = "select * from user where user='"+username+"';";
ResultSet rs = st.executeQuery(sql2);
if(rs != null && rs.next())
{
response.sendRedirect("index.html?err=Username already taken");
}
else
{
String sql = "insert into user values('"+name+"', '"+username+"','"+pass+"',"+cpass+");";
st.executeUpdate(sql);
response.sendRedirect("blank.html");
}
Related
Else statement not working inside while loop
public void loginButton() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/finditdb","root","root");
Statement stmt = con.createStatement();
String usernameInput = usernameField.getText();
String passwordInput = passwordField.getText();
ResultSet rs = stmt.executeQuery("SELECT * FROM finditdb.login WHERE username like '" + usernameInput +"' and password like '" + passwordInput +"'");
while(rs.next()){
String usernameDb = rs.getString("username");
String passwordDb = rs.getString("password");
if(usernameInput.equals(usernameDb) && passwordInput.equals(passwordDb)){
System.out.println("Access Granted..");
}
else {
System.out.println("Access denied..");
}
}
}
You could try this and let me know if it works the way you want it to.
while(true){
if(rs.next()){
String usernameDb = rs.getString("username");
String passwordDb = rs.getString("password");
if(usernameInput.equals(usernameDb) && passwordInput.equals(passwordDb)){
System.out.println("Access Granted..");
break;
}
}
else{
System.out.println("Access denied..");
break;
}
}
We haven't mentioned any exit condition within the while loop parenthesis, so the loop keeps running till no more records are left to be fetched (else will print Access denied and break) or if access is granted (breaks again).
So I am creating an online bank transfer section where the user can transfer money between their account. I have a drop down box where it will show the amount of accounts the user has. I am not sure if I am doing this correctly. Here is my code so far:
transfer-page.jsp
<form name="transfer" action="TransferServlet" method="post">
<%
String email = (String) session.getAttribute("email");
String getAccountType = UserProfileService.getAccountTypeByEmail(email);
int count = UserProfileService.getAmountOfAccounts(email);
%>
From Account: <select name="AccountType">
<%
for(int i = 0; i < count; i++)
{
%>
<option> <%=getAccountType %>
<%
}
%>
</option>
</select>
</form>
Database Class:
public static String getAccountTypeByEmail(String email)
{
// AccountType accountType = new AccountType();
String getAccountType = "";
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT * FROM accountType WHERE email=?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, email);
ResultSet rs = stmt.executeQuery(query);
rs.next();
getAccountType = rs.getString("accountType");
// accountType.setAccountType(getAccountType);
} catch (Exception e)
{
System.out.println(e);
}
// return accountType;
return getAccountType;
}
public static int getAmountOfAccounts(String email)
{
int count = 0;
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT count(*) FROM accountType WHERE email=?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, email);
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
String account = rs.getString("accountType");
count++;
}
} catch (Exception e)
{
System.out.println(e);
}
return count;
}
I do not know under what circumstances you will appear in the drop-down box shows the amount of the account. An account binding more than one bank card?
String getAccountType = UserProfileService.getAccountTypeByEmail(email); your method getAccountTypeByEmail(String email) return only one result,why you loop show it.
I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java
This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 6 years ago.
`
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
PreparedStatement pst = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
String query1 = "SELECT Name FROM Employee WHERE Name=?";
pst = conn1.prepareStatement(query1);
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String name = "";
int count = 0;
while(rs.next()){
title = rs.getString("name");
pst.setString(1, title);
rs1 = pst.executeQuery();
while(rs1.next()){
count++;
if(count % 100 == 0)
System.out.println(count);
}
}
System.out.println(count);
}
}
`
I am selecting value from the very large database based on some value from other database . I am running my select query in a while loop. After running my java code after getting many result , i am getting
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure exception.
I have no idea why this is happening. If you guys have any idea please help
I already read the old questions based on this exception but none of them helps.
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
PreparedStatement pst = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String title = "",query1="";
StringBuffer newQuery = new StringBuffer("SELECT Name FROM Employee WHERE ");
int count = 0;
long nameCount = 0L;
while(rs.next()){
nameCount++;
title = rs.getString("name");
query1 = "Name=? or";
pst = conn1.prepareStatement(query1);
pst.setString(1, title);
newQuery.append(pst.toString().substring(pst.toString().indexOf('N'), pst.toString().length())+" ");
}
if ( nameCount > 0 ){
String Query = newQuery.toString().substring(0,newQuery.toString().length() - 3);
rs1 = conn1.createStatement().executeQuery(Query);
while(rs1.next()){
count++;
if(count % 50 == 0)
System.out.println(count);
}
}
}
}
Using PreparedStatement solves the problem of SQL Injection attack. Now the code is working.
I think this code is optimized, but it may have some syntax error:
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
//String query1 = "SELECT Name FROM Employee WHERE Name=?";
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String name = "";
StringBuffer newQuery = new StringBuffer("SELECT Name FROM Employee WHERE");
int count = 0;
long nameCount = 0L;
while(rs.next()){
nameCount++;
title = rs.getString("name");
newQuery.append(" Name='" + title + "' or");
}
if ( nameCount > 0 ){
newQuery = newQuery.subString( newQuery.length() - 3);
rs1 = conn1.createStatement.executeQuery( newQuery );
while(rs1.next()){
count++;
if(count % 100 == 0)
System.out.println(count);
}
}
}
}
Link failure may be because of so many query execution. Hence I have made it to fire only one or two queries, and you will get all your results.
Why am I getting "parameter index out of range (1>no. of parameters,which is 0)" for the code below?
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
String tabId = lblTableId.getText().trim();
try {
DBConnection db = new DBConnection();
Connection con = db.getConnectionMyWareHouse(Main.dwh.lblSessionWarehouse.getText());
String query1 = "Select DWTableId,DWTableName from datawarehousetable where DWTableId=? and DWTableName=? ";
System.out.println("OG Query ---->"+query1);
PreparedStatement ps1 = con.prepareStatement(query1);
ps1.setString(1, tabId);
ResultSet rs1 = ps1.executeQuery();
String strTN = "";
if(rs1.next())
{
strTN = rs1.getString("DWTableName");
}
String query2 = "Delete from datawarehousetable where DWTableId= ?";
System.out.println("OG Query ---->"+query2);
PreparedStatement ps2 = con.prepareStatement(query2);
ps2.setString(1, tabId);
int rs2 = ps2.executeUpdate();
String query3 = "Drop table " + strTN;
System.out.println("OG Query ---->"+query3);
PreparedStatement ps3 = con.prepareStatement(query3);
ps3.setString(1, tabId);
int rs3 = ps3.executeUpdate();
JOptionPane.showMessageDialog(null, "Table deleted successfully.", "Successful", JOptionPane.INFORMATION_MESSAGE);
con.close();
}
catch(Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error : " + e.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
}
}