I'm trying to connect my application to my database.
I does not give a error, its runs but it doesn't fetch the info.
I've tried run tnsping from the command line to see if the listener is on, and it says that it's ok.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.io.*;
import javax.swing.*;
public class Connector extends JFrame{
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
Connection conn = null;
//Statement stmt = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:dbserver", "scott","tiger");
}
catch(SQLException e)
{ JOptionPane.showMessageDialog(null,e.getMessage(), "Erro na COnexao!",JOptionPane.ERROR_MESSAGE);
}
catch(Exception e)
{ e.printStackTrace();
}
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("SELECT * FROM AnimalM");
System.out.println ("Nome Salario");
if (rset.next()){
System.out.println("Aloooo");
int cod = rset.getInt(1);
String nome = rset.getString(2);
String nome_es = rset.getString(3);
int id = rset.getInt(4);
System.out.println (cod+" "+nome+" "+nome_es+" "+id);
}
rset.close(); //Close ResultSet
stmt.close(); //Close Statement
conn.close(); //Close Connection
}
}
It run until this instruction:
System.out.println ("Nome Salario");
And then nothing else shows, the program stops.
Does anyone have an idea of what might be happening?
I'd recommend stepping through with the debugger in Eclipse to see what's happening. Maybe the query returns no rows.
One design note: This class mixes UI, connection acquisition, and database access into one. A better approach would be do separate these into different classes. Test one feature, put it aside, and let the other classes simply use the functionality that you just implemented and proved to be working fine.
When you have one class doing too much you have no idea where the issue is when things go wrong.
You aren't closing your resources properly, either. Those should be wrapped in individual try/catch blocks.
I'd put all the code into one try/catch finally block and close the resources at the end.
I'd pass the connection into a data access object that would be responsible for acquiring the ResultSet and mapping it into objects or data structures.
I would move all Swing out of the database layer. You can reuse it without Swing that way (e.g. if you switch to a web UI).
Related
I'm coding for hours to insert data into my SQL database, but nothing happens.
I even can't debug Java, because I don't get any output of my console.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author xxx
*/
public class MyServlet extends HttpServlet {
private static final String URL = "jdbc:mysql://localhost:3306/userdata";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final DecimalFormat DF2 = new DecimalFormat("#.##");
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
try {
String myDriver = "com.mysql.jdbc.Driver";
try {
Class.forName(myDriver);
// opening database connection to MySQL server
con = DriverManager.getConnection(URL, USER, PASSWORD);
// getting Statement object to execute query
// the mysql insert statement
String query = "INSERT INTO customers (customer, currency, amount) values ('Name', 'Currency', 100);";
stmt.executeUpdate(query);
// execute the preparedstatement
// executing SELECT query
rs = stmt.executeQuery(query);
con.close();
stmt.close();
rs.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
}
}
What did I wrong, that nothing happens? Even if I use this code for Java-Classes (not Servlets), I only receive an compile error, but without message.
I'm using the IDE Netbeans and mysql DB is the MySQL Workbench. The Java Class is using the main method.
Update:
I've tested following Code with IntelliJ:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/userdata";
String user = "root";
String password = "root";
String query = "Insert into customers (customer, currency, amount) values('Michael Ballack', 'Euro', 500)";
try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement(query)) {
pst.executeUpdate();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
private static class JdbcMySQLVersion {
public JdbcMySQLVersion() {
}
}
I can insert data into the MySQL database.
In Netbeans this code won't work, although I've implemented the MySQLConnector. I don't know why, but Netbeans seems hard to handle.
In the servlet code, I don't see you ever write anything to out. So nothing is being sent back to the browser, even if it compiled. You could write your SQL exception to the out writer you created. To be more precise add this in your exception: out.println(sqlEx.printStackTrace()); That should at least show what exception you are getting back to the browser.
What is the compile error you get outside of a servlet?
This maybe obvious, but to get JDBC stuff to work on your server, you need to have the MySQL server installed, started and configured. The table referenced has to be defined, etc. You could check this outside of the Java servlet environment with the tools provided with MySQL.
your code can not compile, you miss catch exception for second 'try'.
Where do you use this class to run, if you run a java class, this class must contain main() function?
you should use some IDEs like eclipse or IntelliJ to code, it help you detect the error easier.
I found the solution. If you are using Netbeans with the Glassfish-Server and you want your servlet to save data into the database, you have to make sure that Netbeans has installed the Driver of your Database Connector (e.g. MySQL Connector). But you also have to configurate your server (e.g. Glassfish) which will support the DB Connector drivers.
In my case my Server didn't load the DB Connector Driver so the JDBC Code couldn't be executed.
Here's a useful link to configurate the Glassfish Server: https://dzone.com/articles/nb-class-glassfish-mysql-jdbc
I'm making an application with JavaFX, Scene Builder and SQLite. For managing SQLite database I'm using DB Browser
I have 3 fields in SQLite: ID, question, answer
When I press on Button "Add" a method is called and sends text from textaria with question to question tab in SQLite and text from textaria with answer do the same.
ID is a number and is autoincremented when I add these fields to SQLite
I successfully sent data from my window but I don't understand how to get data from SQlite and set it to label and combobox in my window
QuestController:
package card;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
public class QuestController implements Initializable {
#FXML private TextArea ta_questText, ta_answerText;
#FXML private Label lb_numberQuest;
#FXML
private ComboBox<?> idQuest;
#Override
public void initialize(URL location, ResourceBundle resources) {
//register QuestController in Context Class
Context.getInstance().setQuestController(this);
}
#FXML
void addCard(ActionEvent event) {
PreparedStatement preparedStatement;
ResultSet resultSet;
String query = "select * from Cards where ID = ? and question = ? and
answer = ?";
Connection connection = DbConnection.getInstance().getConnection();
try {
String question = ta_questText.getText();
String answer = ta_answerText.getText();
Statement statement = connection.createStatement();
int status = statement.executeUpdate("insert into Cards (question,
answer) values ('"+question+"','"+answer+"')");
if (status > 0) {
System.out.println("question registered");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
DbConnection class:
package card;
import org.sqlite.SQLiteConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
private DbConnection() {
}
public static DbConnection getInstance() {
return new DbConnection();
}
public Connection getConnection() {
String connect_string = "jdbc:sqlite:database.db";
Connection connection = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:database.db");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
}
How can I get all existing ID(numbers) from SQLite and put it to combobox?
How can choose a number(ID) and apply number to a label?
if I choose any number from combobox
How can I apply text with question and answer from SQLite connected to that number to textarias in my window?
Just like the comments in your post, I highly suggest breaking down your codes into layers for better manageability. Good job on starting with your DbConnection class. Additionally, JavaFx already setup some layer for you to start on.
These are the:
View: your FXML file that's created on scene builder
Controller: the JFx controller that FXML forces you to use
Now it is up to you to add more layers to manage your code. I will suggest starting with these:
Model: this will be the main data structure you will work on. For starters, maybe you can follow the structure of your database? Example: class Card with fields id, question, and answer.
Persistence: this Java class will hold your SQL code. This is also responsible for converting the ResultSet object to your model object.
Then finally, keep in mind that your are working with layers. Make sure that their interactions don't leak.
View (FXML) <--> Controller + Model <--> Persistence + Model
To answer your questions:
How can I get all existing ID(numbers) from SQLite and put it to combobox?
Perform an SQL SELECT using your SQLite connection to fetch all the ids. (SELECT id FROM cards perhaps?)
On successful SELECT call, iterate through the ResultSet object. Each iteration should fetch the data from id column, convert it to string (or whatever type your combobox accepts), then add them all. (something like this: comboBox.getItems().add(id))
How can choose a number(ID) and apply number to a label?
How can I apply text with question and answer from SQLite connected to that number to textarias in my window?
Perform an SQL SELECT using your connection, this time add a WHERE clause in the statement to filter results. Since there is a dynamic part in your SQL now, using PreparedStatement will be good. Example: SELECT id, question, answer FROM card WHERE id=?
Using the results of the SQL calls, assign them to the proper JFx Components such as labels and text areas.
Currently im developing a java swing application that I'd like to serve as the GUI for CRUD operations on a MS access database. Currently, everyone on the team that will be using this application updates a spreadsheet on a shareserver. They'd like to switch over to a UI that better suits their purposes, and transition the spreadsheet to a database.
I'm planning on putting an executable jar and the ms access database file on the shareserver. This is where the jar will be accessed.
I don't want users to have to be messing with ODBC settings. Is there a library that can help with this?
UPDATE: Shailendrasingh Patil's suggestion below worked best for me. This took me a little bit of research and the setup was a bit confusing. But I eventually got everything working the way I was hoping. I used Gradle to pull in the necessary dependencies to use UcanAccess.
The following is a snippet from my DatabaseController class:
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseController {
public DatabaseController() {}
public void addOperation(String date, String email, String subject, String body) {
try{
Connection con = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\user\\Desktop\\TestDatabase.accdb;jackcessOpener=CryptCodecOpener","user", "password");
String sql = "INSERT INTO Email (Date_Received, Email_Address, Subject, Message) Values " +
"('"+date+"'," +
"'"+email+"'," +
"'"+subject+"'," +
"'"+body+"')";
Statement statement = con.createStatement();
statement.execute(sql);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(),"Error",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
}
The following class is also required:
import java.io.File;
import java.io.IOException;
import com.healthmarketscience.jackcess.CryptCodecProvider;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import net.ucanaccess.jdbc.JackcessOpenerInterface;
public class CryptCodecOpener implements JackcessOpenerInterface {
public Database open(File fl,String pwd) throws IOException {
DatabaseBuilder dbd =new DatabaseBuilder(fl);
dbd.setAutoSync(false);
dbd.setCodecProvider(new CryptCodecProvider(pwd));
dbd.setReadOnly(false);
return dbd.open();
}
}
I apologize for the bad indentations.
You should use UCanAccess drivers to connect to MS-Access. It is a pure JDBC based and you don't need ODBC drivers.
Refer examples here
Using UCanAccess for the first time for a project and I am having a lot of trouble inserting a row into one of my database tables (in Microsoft Access).
My code makes sense but once I execute I end up getting the same error every time, even though NetBeans is able to connect to my database.
package Vegan;
import java.sql.Connection;
import java.sql.DriverManager;
public class connectionString {
static Connection connection = null;
public static Connection getConnection()
{
try
{
connection = DriverManager.getConnection("jdbc:ucanaccess://C://MyDatabase1.accdb");
System.out.println("---connection succesful---");
}
catch (Exception ex)
{
System.out.println("Connection Unsuccesful");
}
return connection;
}
package Vegan;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DB {
private static ResultSet rs = null;
private static PreparedStatement ps = null;
private static Connection connection = null;
public DB() {
connection = connectionString.getConnection();
}
public void AddTest() {
try {
String sql = "INSERT INTO CategoryTbl(CategoryName) VALUES (?)";
ps = connection.prepareStatement(sql);
ps.setString(1, "Flours");
ps.executeUpdate();
System.out.println("Inserted");
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage().toString());
}
}
After that, when I execute the the AddTest() method, I get this system output:
run:
---connection succesful---
java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:724)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:297)
UCAExc:::3.0.6 null
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:234)
at com.healthmarketscience.jackcess.impl.TableImpl.writeDataPage(TableImpl.java:1375)
at com.healthmarketscience.jackcess.impl.TableImpl.addRows(TableImpl.java:1624)
at com.healthmarketscience.jackcess.impl.TableImpl.addRow(TableImpl.java:1462)
at net.ucanaccess.converters.UcanaccessTable.addRow(UcanaccessTable.java:44)
at net.ucanaccess.commands.InsertCommand.insertRow(InsertCommand.java:101)
at net.ucanaccess.commands.InsertCommand.persist(InsertCommand.java:148)
at net.ucanaccess.jdbc.UcanaccessConnection.flushIO(UcanaccessConnection.java:315)
at net.ucanaccess.jdbc.UcanaccessConnection.commit(UcanaccessConnection.java:205)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:161)
at net.ucanaccess.jdbc.ExecuteUpdate.execute(ExecuteUpdate.java:50)
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.executeUpdate(UcanaccessPreparedStatement.java:253)
at Vegan.DB.AddTest(DB.java:91)
at Vegan.TestDB.main(TestDB.java:17)
BUILD SUCCESSFUL (total time: 1 second)
With no changes being made to the database when I check on it again Access.
What could be causing this, and what does the error message mean? Thank you
"java.nio.channels.NonWritableChannelException" means that the database file cannot be updated. In your case that was because the database file was in the root folder of the Windows system drive (C:\) and mere mortals have restricted permissions on that folder.
Solution: Move the database file to a folder where you have full write access.
I'm trying to insert rows in SQLite embedded DB in java. after adding changes are visible in that program alone. I can't see the changes in sqlite manager. When I try to insert a row in sqlite manager values that inserted which are shown in the program gets deleted. And showing those row that I added using sqlite manager. Please help..
connection class
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class HsqlConn {
//public static void main(String[] args) {
public static Connection hconn = null;
public static Statement hstmt = null;
public static PreparedStatement pst = null;
public static void hConnectDb(){
try{
Class.forName("org.sqlite.JDBC");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("PS/PSDB.sqlite");
hconn = DriverManager.getConnection("jdbc:sqlite::resource:"+resource);
}
catch(Exception se){
//Handle errors for JDBC
se.printStackTrace();
}
}
}
main class using that db
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
hConnectDb();
String sql1 = "Insert into Bill (billNo,date,principal,principalText,custId,dueDate) values (?,?,?,?,?,?)";
pst = hconn.prepareStatement(sql1);
pst.setString(1,BillNoField.getText());
pst.setString(2,dateField1.getText());
pst.setString(3,PrincipalField.getText());
pst.setString(4,PrincipaTextField.getText());
pst.setString(5,custIdField.getText());
pst.setString(6,dueDateField.getText());
pst.executeUpdate();
pst.close();
hconn.close();
JOptionPane.showMessageDialog(null, "saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
According to the documentation of sqlite-jdbc, connection URL strings beginning with "jdbc:sqlite::resource:" are for loading read-only SQLite databases:
2009 May 19th: sqlite-jdbc-3.6.14.1 released.
This version supports "jdbc:sqlite::resource:" syntax to access read-only DB files contained in JAR archives, or external resources specified via URL, local files address etc. (see also the
You need to specify a file in the filesystem containing your SQLite database. On Windows, an example is:
Connection connection = DriverManager.getConnection("jdbc:sqlite:C:/work/mydatabase.db");
and on UNIX-like systems, an example is:
Connection connection = DriverManager.getConnection("jdbc:sqlite:/home/leo/work/mydatabase.db");