i´m trying to use a endpoint to question mysql database in eclipse using tomcat 7 as server but it´s always giving me this error, does someone solved this problem with jdbi
type Exception report
message java.sql.SQLException: No suitable driver found for
jdbc:mysql://127.0.0.1/demo
The code:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.json.JSONException;
import org.json.JSONObject;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
#Path("/jdbiservice")
public class JdbiService {
#Path("{f}")
#GET
#Produces("application/json")
public Response convertFtoCfromInput(#PathParam("f") int f) throws JSONException {
DBI dbi = new DBI("jdbc:mysql://127.0.0.1/demo", "user", "pass");
Handle h = dbi.open();
BatchExample b = h.attach(BatchExample.class);
Something s =b.findById(f);
h.close();
JSONObject jsonObject = new JSONObject(s);
String result = jsonObject.toString();
return Response.status(200).entity(result).build();
}
}
Hi have the jar connector file on the eclipse project path and inside tomcat lib folder.
This worked for me
package com.crunchify.restjersey;
import java.util.List;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import org.json.*;
import org.skife.jdbi.v2.*;
#Path("/sensorservice")
public class SensorService {
#Path("{id}")
#DELETE
public Response deleteSensorById(#PathParam("id") int id) {
///...
try {
DBI dbi = new DBI(SensorService.getDataSource());
Handle h = dbi.open();
SensorInterface si = h.attach(SensorInterface.class);
si.deleteById(id);;
h.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = "Deleted";
return Response.status(200).entity(result).build();
}
private static DataSource getDataSource (){
DataSource ds = null;
InitialContext contex;
try {
contex = new InitialContext();
ds = ( DataSource) contex.lookup("java:comp/env/jdbc/jndiname");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ds;
}
}
at webinf/webxml
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
on tomcat context file
<Resource
name = "jdbc/jndiname"
auth = "Container"
type = "javax.sql.DataSource"
maxActive ="100"
maxIdle = "30"
maxWait = "10000"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost:3306/schema"
username = "user"
password = "pass"
/>
You should include the mysql driver in your dependencies.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
Related
This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 5 years ago.
I am writing servlet to connect with mysql database using mysqlconnector java but it is giving error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
I have tried same with core java using the same driver it is connecting to mysql and query is also running but using servlet it is not working.
my code is for servlet is:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("userName");
String p = request.getParameter("password");
String e = request.getParameter("email");
String c = request.getParameter("course");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/phpmyadmin/saiiff","root", "");
PreparedStatement ps = conn
.prepareStatement("insert into eemeze values(?,?,?,?)");
ps.setString(1, n);
ps.setString(2, p);
ps.setString(3, e);
ps.setString(4, c);
int i = ps.executeUpdate();
if (i > 0)
out.print("You are successfully registered...");
} catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
Download the mysql jar from http://www.java2s.com/Code/JarDownload/com.mysql/com.mysql.jdbc_5.1.5.jar.zip
And Build on classpath
I am getting below error while executing java code in Eclipse (I am not using Maven)
Exception in thread "main" java.lang.NoSuchMethodError: org.codehaus.jackson.JsonFactory.enable(Lorg/codehaus/jackson/JsonParser$Feature;)Lorg/codehaus/jackson/JsonFactory;
at org.apache.avro.Schema.<clinit>(Schema.java:88)
at org.apache.avro.Schema$Parser.parse(Schema.java:997)
at com.rishav.avro.AvroExampleWithoutCodeGeneration.serialize(AvroExampleWithoutCodeGeneration.java:36)
at com.rishav.avro.AvroExampleWithoutCodeGeneration.main(AvroExampleWithoutCodeGeneration.java:94)
I am using jars:
avro-1.8.2.jar
java-jason.jar
jason-simple-1.1.1.jar
org.apache.sling.commons.json-2.0.6-sources.jar
org.apache.sling.launchpad-9
jackson-core-asl-1.1.0.jar
jackson-mapper-asl-1.1.0.jar
Line 36 --> Schema schema = new Schema.Parser().parse(new File("StudentActivity.avsc"));
package com.rishav.avro;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
//import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.simple.JSONObject;
public class AvroExampleWithoutCodeGeneration {
public void serialize() throws JsonParseException, JsonProcessingException, IOException {
InputStream in = new FileInputStream("StudentActivity.json");
// create a schema
Schema schema = new Schema.Parser().parse(new File("StudentActivity.avsc"));**// THIS IS LINE 36**
// create a record to hold json
GenericRecord AvroRec = new GenericData.Record(schema);
// create a record to hold course_details
GenericRecord CourseRec = new GenericData.Record(schema.getField("course_details").schema());
// this file will have AVro output data
File AvroFile = new File("resources/StudentActivity.avro");
// Create a writer to serialize the record
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
dataFileWriter.create(schema, AvroFile);
// iterate over JSONs present in input file and write to Avro output file
ObjectMapper mapper = new ObjectMapper();
Iterator it= (Iterator) mapper.readValue(new JsonFactory().createJsonParser(in), JSONObject.class);
while (it.hasNext())
{
//for (Iterator it = mapper.readValues(new JsonFactory().createJsonParser(in), JSONObject.class); it.hasNext();) {
JSONObject JsonRec = (JSONObject) it.next();
AvroRec.put("id", JsonRec.get("id"));
AvroRec.put("student_id", JsonRec.get("student_id"));
AvroRec.put("university_id", JsonRec.get("university_id"));
LinkedHashMap CourseDetails = (LinkedHashMap) JsonRec.get("course_details");
CourseRec.put("course_id", CourseDetails.get("course_id"));
CourseRec.put("enroll_date", CourseDetails.get("enroll_date"));
CourseRec.put("verb", CourseDetails.get("verb"));
CourseRec.put("result_score", CourseDetails.get("result_score"));
AvroRec.put("course_details", CourseRec);
dataFileWriter.append(AvroRec);
} // end of for loop
in.close();
dataFileWriter.close();
} // end of serialize method
public void deserialize () throws IOException {
// create a schema
Schema schema = new Schema.Parser().parse(new File("resources/StudentActivity.avsc"));
// create a record using schema
GenericRecord AvroRec = new GenericData.Record(schema);
File AvroFile = new File("resources/StudentActivity.avro");
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(AvroFile, datumReader);
System.out.println("Deserialized data is :");
while (dataFileReader.hasNext()) {
AvroRec = dataFileReader.next(AvroRec);
System.out.println(AvroRec);
}
}
public static void main(String[] args) throws JsonParseException, JsonProcessingException, IOException {
AvroExampleWithoutCodeGeneration AvroEx = new AvroExampleWithoutCodeGeneration();
AvroEx.serialize();
AvroEx.deserialize();
}
}
You can put this instead:
Schema schema = new Schema.Parser().parse.newFile("resources/StudentActivity.avsc");
I was starting out with google map Api's. Following some examples on the internet.I came up with these code. I was able to get the Json code quite easily by crating HttpURLCOnnection but somehow I am getting a runtime error.Somehow i am unable to create a Json Object.I searched quite a bit,but didn't find any relation between JSONObject and Runtimeerror
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
public class Parser {
public static void main(String args[])
{
String response="";
int lat1=20270000,lon1=85520000,lat2=20264500,lon2=85835500;
String urlString="https://maps.googleapis.com/maps/api/directions/json?origin="+Double.toString((double)lat1/1E6)+","+Double.toString((double) lon1/1E6)+"&destination="+Double.toString((double)lat2/1E6)+","+Double.toString((double) lon2/1E6)+"&sensor=true";
HttpURLConnection urlConnection= null;
URL url = null;
try{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp;
while((temp = bReader.readLine()) != null){
response += temp;
}
System.out.println(response);
bReader.close();
inStream.close();
urlConnection.disconnect();
}
catch(Exception e){}
ArrayList<Bundle> list = new ArrayList<Bundle>();
try {
System.out.println(response.toString()); // uptil here every thing is fine..... I am getting correct Json text.
JSONObject jsonObject = new JSONObject(response); //I am getting a runtime error in this line. Can't figure out the reason
System.out.println(jsonObject);
JSONArray routesArray= jsonObject.getJSONArray("routes");
JSONObject route = routesArray.getJSONObject(0);
JSONArray legs = route.getJSONArray("legs");
JSONObject leg = legs.getJSONObject(0);
JSONObject durationObject = leg.getJSONObject("duration");
String duration = durationObject.getString("text");
System.out.println("egferg"+duration);
}
catch(Exception e1){e1.printStackTrace();}
}
}
I'm trying to set up a connection to my database through a Tomcat JNDI resource. I've been looking at many articles today and I can't seem to find an answer.
In my server.xml I have:
<GlobalNamingResources>
<Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="tomcat" password="...."
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>
.....
</GlobalNamingResources>
In my web service, I attempt to access the resource with:
InitialContext ctx = new InitialContext();
DataSource data = (DataSource)ctx.lookup("java:comp/env/jdbc/MyDB");
Connection conn = data.getConnection();
When I run the code, I get this exception:
Nov 2, 2011 1:06:20 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
...
I have the newest mysql-connector-java-5.1.18-bin.jar in both my web-app's lib and my tomcat lib.
Can you please help me get this working?
I use this code, with only the name of the resource, and it works:
private Connection getConnection(){
final Context ctx = new InitialContext();
final DataSource ds = (DataSource) ctx.lookup("jdbc/MyDB");
if (ds != null)
{
return ds.getConnection();
}
else
{
}
}
We just need to mention the jndi name after java:
In your case:
InitialContext ctx = new InitialContext();
DataSource data = (DataSource)ctx.lookup("java:/jdbc/MyDB");
Connection conn = data.getConnection();
Because you configured in your server.xml as below:
<GlobalNamingResources>
<Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="tomcat" password="...."
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>
.....
</GlobalNamingResources>
My solution was to switch to a properties file for the database information and then utilize it with entity manager.
import java.io.FileReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import org.eclipse.persistence.config.EntityManagerProperties;
import org.eclipse.persistence.config.PersistenceUnitProperties;
...
Properties properties = new Properties();
FileReader fr = new FileReader(Constants.Config.getPropertiesFile());
properties.load(fr);
// connect to the database
Map<String,String> emMap = new HashMap<String,String>();
emMap.put(PersistenceUnitProperties.APP_LOCATION, Constants.Config.getAppDir());
emMap.put(EntityManagerProperties.JDBC_USER, properties.getProperty("db.username"));
emMap.put(EntityManagerProperties.JDBC_PASSWORD, properties.getProperty("db.password"));
// iterate over these properties attempting to read them in and connect to the url
List<?> dbProps = Collections.list(properties.keys());
Collections.sort(dbProps, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(((String)o2));
}
});
for(Object propKey : dbProps){
// support multiple database key/values in the eform db.url, db.url1, ... db.urlN
if(!propKey.toString().matches("db.url\\d*")){
continue;
}
String dbLocation = properties.getProperty(propKey.toString());
try {
if(dbLocation == null) continue;
emMap.put(EntityManagerProperties.JDBC_URL, dbLocation);
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("db", emMap);
em = entityManagerFactory.createEntityManager();
// ensure we're connected by executing a no-op query
em.createNativeQuery("select current_database()").getSingleResult(); // will only work for postgresql
properties.put("db.connected", dbLocation);
break;
}
catch (javax.persistence.PersistenceException e) {
Utility.logger(DataHolder.class).error("Couldn't connect to " + dbLocation);
}
}
I have been searching the web for a connection between my Android simulator and a MySQL db.
I've found that you can't connect directly but can via a web server. The web server will handle my request from my Android.
I found the following code on Hello Android, but I don't understand. If I run this code on the simulator, nothing happens; the screen stays black.
Where does Log.i land, in the Android screen, the error log, or somewhere else?
Can somebody help me with this code?
package app.android.ticket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class fetchData extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//call the method to run the data retreival
getServerData();
}
public static final String KEY_121 = "http://www.jorisdek.nl/android/getAllPeopleBornAfter.php";
public fetchData() {
Log.e("fetchData", "Initialized ServerLink ");
}
private void getServerData() {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Logging messages go in the Log cat. You could also use LogCat Reader.