I have the following methods that are encountering some sort of failure with my database. No error is being written to my console, so I'm confused. I'm using JDBC and Google AppEngine. Can anyone help me, please? Thanks.
public List<Bulletin> getApprovedBulletins() {
List<Bulletin> bulletins = new ArrayList<Bulletin>();
try {
Connection connection = getConnection();
Statement statement = connection.createStatement();
statement.executeQuery("select * from bulletins where approved = true");
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
Bulletin bulletin = new Bulletin();
bulletin.setId(resultSet.getInt("id"));
bulletin.setDate(resultSet.getDate("bulletin_date"));
bulletin.setName(resultSet.getString("name"));
bulletin.setSubject(resultSet.getString("subject"));
bulletin.setNote(resultSet.getString("bulletin"));
bulletins.add(bulletin);
}
resultSet.close();
connection.close();
return bulletins;
}
catch (Exception e) {
System.out.println(e.toString());
}
return null;
}
private Connection getConnection() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/cpc";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
return null;
}
return conn;
}
If you're using eclipse check the markers tab for errors. Note that the driver must be in the application server folder as well in order to work. Not sure why you don't get any errors in the console though...
Problem solved. I found a place to print out a message to my console, and it turns out I needed to add the following to appengine-web.xml, which I have done.
<sessions-enabled>true</sessions-enabled>
Related
I exported a java api abc.war file deployed into the "server", which returns the null([]) values, when I am calling get method from the Postman. This is working fine in local system but not in server.
Connection con= getConnection();
List<QuestionsModel> lstQuestions=new ArrayList<QuestionsModel>();
try
{
if(con!=null)
{
CallableStatement cstmt = null;
ResultSet rs = null;
cstmt = con.prepareCall("{call GetQuestions()}");
cstmt.execute();
rs = cstmt.getResultSet();
while (rs.next()) {
QuestionsModel questionsModel=new QuestionsModel();
questionsModel.setQuestionID(rs.getInt("QuestionID"));
questionsModel.setQuestion(rs.getString("Question"));
lstQuestions.add(questionsModel);
}
con.close();
System.out.println("Hello from GetQuestions Repository");
return lstQuestions;
}
}
catch (SQLException e) {
e.printStackTrace();
}
return lstQuestions;
Expected : Return list of objects(QuestionData)
Errors: No errors.
in Windows application, webRequest.GetResponse() Behavior :
1) First time, I tried with "invalid user name/ credentials" and getting the below error.
"ERROR: The remote server returned an error: (407) Proxy
Authentication Required."
and now I am giving valid "user name and credentials" -> getting the response
2) Now the reverse scenario,
i.e I called the API with valid userName and password -> working
after this, if I try with an invalid credential, I am getting the response.
Code Snippet:
private void button1_Click(object sender, EventArgs e)
{
label1.Text = string.Empty;
var webProxy = new WebProxy("http://proxy:80/",true)
{
Credentials = new NetworkCredential("UserName", "PassWord"),
UseDefaultCredentials = false
};
WebRequest.DefaultWebProxy = webProxy;
try
{
var webRequest = (HttpWebRequest)WebRequest.Create("http://Google.co.in");
webRequest.Proxy = webProxy;
webRequest.Timeout = 30 * 1000;
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
label1.Text = string.Format("WebRequest Response Code : {0}. Web Request Status : {1}", webResponse.StatusCode, webResponse.StatusDescription);
}
}
catch (Exception ex)
{
label1.Text = ex.Message;
}
finally { WebRequest.DefaultWebProxy = null; }
}
I am not able to find the exact reason, how the call become success, please help me to understand the above scenario.
I'm trying to create desktop App (scenebuilder) and I want to retrieve path of Image from DATABASE (SQLITE) and Attach it to button to open it in ImageView but I'm facing a problem while doing that.
Note: I'm trying to learn Java
My code
#FXML
private ImageView imageView;
#FXML
void btn10 (ActionEvent event) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sogeclair.sqlite");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "SELECT * FROM image WHERE rowid = 1" ;
System.out.println(sql);
ResultSet rs = stmt.executeQuery( sql );
while ( rs.next() ) {
String path=rs.getString("imaging");
imageView.setImage(new Image(path));
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
and I got this in result
Opened database successfully
SELECT * FROM image WHERE rowid = 1
java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
Deleting directory C:\Users\Lenovo\Documents\NetBeansProjects\sogece\dist\run538077077
jfxsa-run:
BUILD SUCCESSFUL (total time: 10 seconds)
and MyDatabase
All comments are welcome :D help me please :D
This is code from a program I wrote that retrieves an image blob from sqlite. You can download and run the program from here. It's running, but it's an incomplete program.
In your code, once you get the image using ideas from my code then just use that image to set your ImageView.
String sqlTCNote = "SELECT * FROM Company;";
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:contactFX.db");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(sqlTCNote))
{
while(rset.next())
{
Company c1 = new Company();
c1.setName(rset.getString("company_name"));
c1.setShortName(rset.getString("short_name"));
c1.setStreet(rset.getString("street"));
c1.setCity(rset.getString("city"));
c1.setState(rset.getString("state"));
c1.setZip(rset.getString("zip"));
c1.setPhoneNumber(rset.getString("phone_number"));
c1.setTollFreeNumber(rset.getString("toll_free_number"));
c1.setEmailAddress(rset.getString("email_address"));
c1.setMissionStatement(rset.getString("mission_statement"));
c1.setPersonalNote(rset.getString("personal_note"));
c1.setWebSiteAddress(rset.getString("website_address"));
//This is the part you are interested in!
InputStream input = rset.getBinaryStream("image");
InputStreamReader inputReader = new InputStreamReader(input);
if(inputReader.ready())
{
File tempFile = new File("tempFile.jpg");
FileOutputStream fos = new FileOutputStream(tempFile);
byte[] buffer = new byte[1024];
while(input.read(buffer) > 0){
fos.write(buffer);
}
Image image = new Image(tempFile.toURI().toURL().toString());
c1.setImage(image);
}
for(int i = 0; i < 10; i++)
{
c1.addEmployee(new Employee());
}
companyData.add(c1);
}
}
catch(SQLException ex)
{
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
I'm playing with Sonarqube plugin for Jenkins. How can I effectively solve this trivial violation he is complaining about without changing the logic?
Note: I need to validate the connections separetely ( ConnectionManager, statistics, keepAlive, .. ).
`
public void executeProcedure( final RequestProcessor consumer ) throws SQLException {
final String procedure = consumer.getProcedure();
final String idUrl = consumer.getIdUrl();
final PreparedStatementRegisterer stmRegisterer = consumer.getRegisterer();
// Autoclosable removed to allow ad hoc connection validation
Connection conn = null;
boolean execSuccess = false;
try{
conn = newConnection();
conn = checkOrChangeConnection(conn, false);
boolean hasResultSet = false;
try( CallableStatement statement = (OracleCallableStatement)conn.prepareCall(procedure) ){
...
stmRegisterer.prepareStatement(statement, idUrl);
statement.setQueryTimeout(QUERY_TIMEOUT);
hasResultSet = statement.execute();
execSuccess = true;
if(hasResultSet){
...
try ( ResultSet rs = statement.getResultSet() ) {
while ( rs.next() ) {
consumer.handleRow( rs );
}
}
}else{
...
consumer.getFieldsFromResult( statement );
}
}
}catch(Exception ex){
LOGGER.log( LogEntries.StorProcErr, ex.getMessage() );
throw new Exception( (!execSuccess ? "Error preparing and executing statement.":"Error during results reading.")+" Cause: "+ex) );
}finally{
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("\n Error closing connection on executeStoredProc. Cause: "+e+" \n"); // log
}
}
}
My idea is to add some more logging and re-throw the same exception after the log "StorProcErr". Is there a better approach?
Thanks
I am getting this error while trying to connect to timesten DB configured in my system:
java.sql.SQLException: Problems with loading native library/missing methods: no ttJdbc1121 in java.library.path
Here is my code:
try {
Class.forName("com.timesten.jdbc.TimesTenDriver");
conn = DriverManager
.getConnection("jdbc:timesten:direct:dsn=TT_Alias");
System.out.println(conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using java 5 & attached ttjdbc5.jar in the build path.
can someone help please?
ttJdbcCS1122.dll is in bin folder of TimesTen home please copy that to lib folder, now start running you program it will work if rest of configuration is correct.
// /JDBC Driver
static final String JDBC_DRIVER = “com.timesten.jdbc.TimesTenDriver”;
static final String DB_URL = “jdbc:timesten:client:TTC_Server=serverIp;TTC_Server_DSN=DSN;TCP_PORT=PortNo”;
// DB Credential
static final String username = “***”;
static final String password = “****”;
System.out.println(“Registering database …”);
Class.forName(JDBC_DRIVER);
//Connecting to db
System.out.println(“Connecting to database …”);
conn = DriverManager.getConnection(DB_URL, username, password);