I am trying to validate a database (phpMyadmin) using Username and Password. I need to search in all the tables (25 tables in my database) for checking if the given username and password are present (Authentication) or not. Can anyone provide the query to search entire table using the given username and password?
Below is my code
public class Dbclass {
/**
* #param args
*/
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
ResultSetMetaData metaData = null;
String DB_URL="com.mysql.jdbc.Driver";
String USER="java";
String PASS="redhat";
String username;
String password;
ResultSet rs;
public ResultSet dbConnection(String query)
{
//STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
try {
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
//sql = "SELECT username,password FROM Employees";
rs = stmt.executeQuery(query);
while(rs.next()){
//Retrieve by column name
username = rs.getString("user_name");
password = rs.getString("password");
//Display values
System.out.print("User_name: " + username);
System.out.print(",Password: " + password);
}
Authentication obj=new Authentication();
obj.userLogin(username,password);
//STEP 6: Clean-up environment
//rs.close();
//return rs;
stmt.close();
conn.close();
} catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException es) {
//TODO Auto-generated catch block
es.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(conn!=null){
conn.close();
}
if (rs != null) {
rs.close();
}
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return rs;
}
}
I guess you're looking for a where clause. Something like below.
SELECT username,password FROM Employees where username='usernm' and password='pwd'
If required, you can add UNION to merge more such queries, but not recommended due to performance issues.
Related
I'm trying to display a list of the names of people in the database from the terminal, but not sure about how I would go about this. Right now I'm using a prepared statement
public static void showNames() throws SQLException {
Statement stmt=null;
Connection conn=null;
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String selectTable="SELECT * FROM userInfo;";
stmt.execute(selectTable);
}
You're close.
Below code is not a complete answer, but hopefully enough to get you moving in the direction of obtaining a complete answer. The below code is basically the code you posted with some modifications.
public static void showNames() throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
String selectTable="SELECT * FROM userInfo;";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
rs = stmt.executeQuery(selectTable);
while (rs.next()) {
Object obj = rs.getObject("name of column in database table USERINFO");
System.out.println(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}
You didn't post the structure of database table USERINFO, so replace name of column in database table with the actual column name.
By the way, there are many examples of how to do this on the Internet, for example Processing SQL Statements with JDBC.
when i wrote function instead of procedure, it compiled.
CREATE OR REPLACE function ilce_gtr
(
p_ilkodu number
)
RETURN VARCHAR2 AS
p_geridonen varchar2(1000);
begin
for rec in(SELECT ADI FROM ILCE WHERE Y_IL=p_ilkodu)
loop
p_geridonen := p_geridonen || '|' || rec.ADI;
end loop;
return p_geridonen;
end;
/
then i created xml via web method, it was successful.
#WebMethod
public String get_ilce (int p_ilkodu) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "SELECT ILCE_GTR('" + p_ilkodu + "') FROM DUAL";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
deger = rs.getString(1);
}
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}
I want to do the same for inserting to database, can u help me?
#WebMethod
public String add_ilce (int yourInput) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "INSERT INTO DUAL" + "(yourAttributeName)" +"VALUES (?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, yourInput);
preparedStmt.execute();
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}
EDIT: I suggest you to use DAO approach for such scenarios, check here: Data access object (DAO) in Java
EDIT: I edited the post now it must work as it should be, sorry I had some mistakes
web service didnt appear on localhost, there are others.
#WebMethod
public String add_ilce (String p_no, int p_tplm) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "INSERT INTO DUAL" + "TEMP_TAHAKKUK_AG(ABONENO,TOPLAM)" +"VALUES ('p_no','p_tplm')";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
deger = rs.getString(1);
}
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}
I have the following code to POST data to a database from a web service. I am using the RESTful web service and I am connecting to a Microsoft Azure Database. I get this error message on the server run mode ->'Resource not available". Can someone help me with this issue ?
#Path("/addcar/{CSID}/{PID}/{LicensePlateNumber}/{RegistrationNumber}/{CarModel}/{MakeYear}")
#POST
#Produces(MediaType.TEXT_PLAIN)
#Consumes (MediaType.APPLICATION_FORM_URLENCODED)
public String insertdata(#PathParam("CSID") String csid,
#PathParam("PID") String pid,
#PathParam("LicensePlateNumber") String lpn,
#PathParam("RegistrationNumber") String rn,
#PathParam("CarModel") String carmodel,
#PathParam("MakeYear") String makeyear) throws ServletException,
IOException, SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
PreparedStatement query = null;
String myString = null;
System.out.println(csid+ ","+ pid +","+lpn + ","+rn + ","+carmodel +","+ makeyear);
//Car car = new Car();
//car.newcar(csid, pid, lpn, rn, carmodel,makeyear);
String DB_URL = "jdbc:sqlserver://nysj1rpznm.database.windows.net:1433;database=gparkdb;user=gpark#nysj1rpznm;password=Technology00000;encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
String USER = "gpark";
String PASS = GlobalUtil.PASS;
try{
//STEP 2: Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql = "INSERT into gpark_cars(CSID,PID,LicensePlateNumber,RegistrationNumber,CarModel,MakeYear) VALUES("+csid+""+ pid +""+ lpn+ ""+ rn+ ""+ carmodel+""+ makeyear+")";
ResultSet rs2 = stmt.executeQuery(sql);
System.out.println(sql);
stmt.executeUpdate(sql);
conn.close();
stmt.close();
conn.close();
}
catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return "Vehilce added";
//System.out.println("Goodbye!");
}
I have been trying this for a few hours now but with no success. I downloaded the JDBC driver and it shows that it is one of my referenced libraries under my Package Explorer in Eclipse but every time I try to run my code I get errors. My database is fine as I can change it and view it from the MySQL Command Line Client.
I actually followed a guides directions on how to do it, only replacing the information from their database to information about mine.
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle Errors For JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle Errors for Class.forName
e.printStackTrace();
} finally {
//Finally Block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
//Nothing We Can Do
}
try {
if (conn != null)
conn.close();
} catch (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
Here is the error I get http://pastebin.com/hLSxV3aq
I am new to jsp pages and trying to make a login page by checking username and password from the database. Here is the code:
protected void CheckUser(String username, String password)
{
try {
connect();
PreparedStatement preparedStatement = con.PreparedStatement(
"SELECT * Users WHERE username = ? AND password = ?");
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
ResultSet rs = (ResultSet) preparedStatement.executeQuery();
} catch (Exception e) {
System.out.println("cannot connect");
e.printStackTrace();
}
}
I get the following error for con.PreparedStatement
The method PreparedStatement(String) is undefined for the type Connection
Can anyone help me with this?
Thanks
Edit: Here is my connection function:
static String dbUrl="jdbc:mysql://localhost:3306/Bank";
static String username="root";
static String password="";
static Connection con=null;
public static void connect ()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=(Connection) DriverManager.getConnection(dbUrl,username,password);
System.out.println("Connected!");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("not connected");
}
}
You spelled the method wrong Connection#prepareStatement(String sql) throws SQLException.
It should be con.prepareStatement, not con.PreparedStatement.
You have to create a Prepared Statement by doing PreparedStatement preparedStatement = con.prepareStatement("your Query");
You need the from keyword in your Query.
Hence, your code should look like
PreparedStatement preparedStatement = con.prepareStatement("SELECT * from Users WHERE username = ? AND password = ?");
Not sure about other stuff, but your query is wrong considering its not an typo, will throw SQLException.
It should be
"SELECT * FROM Users WHERE username = ? AND password = ?"
^^^^
||||
here