I am using this code to create a login webservice to database
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){};
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = '+name+' and prenom = '+lastname+' ";
st.close();
cn.close();
System.out.println("success");
return "login";
}
}
My code is working but I don't know how to extract the result of the sql request ( here id )
Are there any suggestions to this issue? Please help!
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){
e.printStackTrace();
}
try {
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = "+name+" and prenom = "+lastname+" LIMIT 1";
ResultSet res = st.executeQuery(req);
if(res.first()) {
String id = res.getString("id");
System.out.println("id = "+id);
} else {
System.out.println("not found foo!");
}
}
catch (SQLException s){
s.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
st.close();
cn.close();
}
return "login";
}
}
Related
i am using volley to fetch data from database.I always get null pointer error. I don't know whats the error. it always executes onErrorResponse() (error.null) and shows this in my logcat
BasicNetwork.performRequest: Unexpected response code 301
here is my java method to fetch data from php file .
private void fetchChatThread() {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages=new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
Toast.makeText(Chat_Rooms.this, messages.getSender_id(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queue
addToRequestQueue(strReq);
}
here is my private that loads data from php to objects
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String commentId = commentObj.getString("id");
String commentText = commentObj.getString("message");
String createddate = commentObj.getString("date");
String commentuser_id = commentObj.getString("user_id_fk");
URL url;
Bitmap image, image1;
try {
url = new URL(Base_URL.BASE_URL_IMAGES + "user_profile_pictures" + commentuser_id + ".jpg");
image1 = BitmapFactory.decodeStream(url.openStream());
image = getResizedBitmap(image1, 50);
} catch (Exception e) {
image = null;
e.printStackTrace();
}
Users user;
user = new Users(commentuser_id, String_username.user_name, image);
Messages message = new Messages();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createddate);
message.setSender_id(commentuser_id);
message.setUser(user);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}
#Override
protected void onPostExecute(ArrayList<Messages> messageArrayList) {
Collections.reverse(messageArrayList);
chatroom_adapter.notifyDataSetChanged();
if (chatroom_adapter.getItemCount() > 1) {
rec_chatBubble.getLayoutManager().smoothScrollToPosition(rec_chatBubble, null, chatroom_adapter.getItemCount() - 1);
}
}
}
TRY THIS
private void fetchChatThread(final String count) {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.d("response error", response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages = new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
}
}) {
#Override
protected HashMap<String, String> getParams() {
HashMap<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
myparams.put("count", count);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queueok
addToRequestQueue(strReq);
}
AND THIS
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
messageArrayList.clear();
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String Id = commentObj.getString("id");
String Text = commentObj.getString("message");
String date = commentObj.getString("date");
String yuser_id = commentObj.getString("user_id");
Messages message = new Messages();
message.setId(Id);
message.setMessage(Text);
message.setCreatedAt(date);
message.setSender_id(yuser_id);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}
So i created a database table in intellij and i made a javafx project and it's connected to my server(localhost)
now i'm getting errors here
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
it says I'm unable to access the table
this is the method
public boolean isLogin(String user,String pass) throws SQLException
{
PreparedStatement preparedStatement = null ;
ResultSet resultSet = null;
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
try
{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,user);
preparedStatement.setString(2,pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
//TODO: handle exception
}
finally {
preparedStatement.close();
resultSet.close();
}
}
and the other error here
if (loginModel.isLogin(userAction.getText(), passAction.getText()))
and this line too
resultSet.close();
and I guess they are related and i don't know how to fix this
this is the other code
#FXML
public void Login(ActionEvent event) {
try {
if (loginModel.isLogin(userAction.getText(), passAction.getText())) {
isConnected.setText("Username & password is correct");
}
else
{
isConnected.setText("Check your username or password");
}
} catch (SQLException e)
{
isConnected.setText("Check your username or password");
//TODO Auto-generated catch block
e.printStackTrace();
}
}
I having a problem to run below Java code. I couldn't find the DB.java class.
ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
System.out.print(rs.getString("pid"));
System.out.print(rs.getString("name"));
System.out.print(rs.getString("price"));
System.out.print(rs.getString("ava_qty"));
}
I'm using Glassfish server. Can someone help me to write the DB.java class?
The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:
https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm
Example code for future reference:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class found");
int no_of_rows = 0;
try {
Connection con = DriverManager.getConnection (
"jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
while (rs.next()) {
no_of_rows++;
}
System.out.println("There are "+ no_of_rows + " record in the table");
} catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}
I have been getting "not all code paths return value" in the following code. I have the code below. I think I am returning appropriately but still there is an error.
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
You forgot a return statement in the first if statement.
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
-->return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
I’m trying to write a method to get the string from the SQL INSERT query to the DB, with an input array as the number of columns using JDBC:
public String methodtest(String ListofColumns)
{
String query = "INSERT INTO" + TableName + "(" + ListOfColumns + ")";
try
{
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
While (rs.next())
{
String result = rs.getString(query);
System.out.println("The SQL query is " + result);
}
}
catch (SQLException sqlEx)
{
e.printStackTrace();
}
finally
{
rs.close();
}
}
Can you see any mistake?
Thanks, Monkawee, for the advice.
You can use the following pattern:
public string methodtest(Array listofcolumns)
{
try{
<Connection string path>
<DB connection method>
<Query string>
<Execution>
<Reset Object>
}
catch(SQLException sqlEx){
// handle exception
}
catch(Exception ex){
// handle other exceptions if any
}
finally{
<Close connection and other resources like PreparedStatement>
}
}