I am trying to make a new user in a Mysql database using java code but the code is not working. This is the Database class which initializes the database connection and creates a user, sets the password, etc.
package app;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
public static MysqlDataSource dataSource;
public static void InitializeData() {
dataSource = new MysqlDataSource();
dataSource.setUser("Quiz");
dataSource.setPassword("Give the quiz");
dataSource.setServerName("localhost");
dataSource.setPort(3306);
dataSource.setDatabaseName("QUIZDATA");
Connection con = Main.getConnection();
try {
Statement st2 = con.createStatement();
st2.execute("CREATE TABLE IF NOT EXISTS Subject1(Question VARCHAR, Option1 VARCHAR, Option2 VARCHAR, Option3 VARCHAR, Option4 VARCHAR, Answer VARCHAR)");
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
And here is my Main class.
package app;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import java.sql.Connection;
import java.sql.SQLException;
public class Main extends Application {
#Override
public void start(Stage stage) throws Exception
{
Parent scene = FXMLLoader.load(getClass().getResource("quiz.fxml"));
stage.setTitle("Quiz");
stage.setScene(new Scene(scene));
stage.show();
}
public static void main(String[] args)
{
launch(args);
Database.InitializeData();
}
public static Connection getConnection()
{
Connection con = null;
try
{
con = Database.dataSource.getConnection();
}
catch (SQLException e)
{
Alert alert = new Alert(Alert.AlertType.ERROR, "Database error", ButtonType.OK);
alert.showAndWait();
}
return con;
}
}
But when I am scanning for any new server in the Mysql workbench, it is not showing any new server.
Add:- When I am right clicking on the blank area(Mysql Workbench), there is a option to "to add connections from clipboard"(Although I don't know what it is doing), it is returning an error :- "Could not parse connection parameters from string "Give the quiz" " (which is the password)"
But when I am scanning for any new server in the Mysql workbench, it
is not showing any new server.
This is not related to your program. First, you need to make sure that your MySQL database is running and then try to execute your program.
Apart from this, although you will be able to run your program once you ensure that your MySQL server is up and running, your program has not been designed well e.g. you should consider the following:
MysqlDataSource dataSource should be marked as private and then you should have public getter for it
Connection getConnection() should be defined in your class Database
You should have constructors and field getters and setters in your class Database
Please note that the above-mentioned points are just a few recommendations and it is not a complete list. I recommend you understand OOPS concept well and apply it in all your programs.
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.
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.
Yes, it's that newbie to Vaadin, again. This time, I'm trying to see if I can do one of the most basic of tasks: connect to a database.
We use MS SQL Server here (version 2012, I believe) and we've been able to connect to it fine in two other Java programs that I've written. When attempting to do the same thing using a newly-created Vaadin project, however, I am told that No suitable driver found for jdbc:sqlserver://192.168.0.248;databaseName=job_orders_2014. I have checked and made sure that all three .jars from Microsoft are in the build path: sqljdbc.jar, sqljdbc4.jar, and sqljdbc41.jar.
Here's the ConnectionManager class that I've written which only tests whether or not it can get a connection:
package info.chrismcgee.sky.vaadinsqltest.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;
public class ConnectionManager {
Logger logger = Logger.getLogger(ConnectionManager.class.getName());
private static final String USERNAME = "web";
private static final String PASSWORD = "web";
private static final String CONN_STRING = "jdbc:sqlserver://192.168.0.248;databaseName=job_orders_2014";
public ConnectionManager() throws SQLException, ClassNotFoundException {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
}
}
The result is the SQLException message I mentioned earlier. I've tried it both with and without that Class.forName... line, which is apparently only necessary for Java versions below 7 (and we're using version 8). When that line is enabled, I get a ClassNotFoundException instead.
What gives?
EDIT 04/01/2015: To help clarify how this ConnectionManager class is called, I am simply creating an instance of it from the main class, thusly:
package info.chrismcgee.sky.vaadinsqltest;
import java.sql.SQLException;
import info.chrismcgee.sky.vaadinsqltest.dbutil.ConnectionManager;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
#Theme("vaadinsqltest")
public class VaadinsqltestUI extends UI {
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = VaadinsqltestUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
ConnectionManager connMan = new ConnectionManager();
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
layout.addComponent(new Label("Thank you for clicking"));
}
});
layout.addComponent(button);
}
}
You need your dependencies in your runtime environment.
Please have a look at this answer here at stackoverflow:
https://stackoverflow.com/a/19630339
I am new to programming and i am trying to make a connection from my program to database but when i make the code,error occurred on line 34 (package con.msql.jdbc does not exit).Can u tell me why??help me
code :
package Absensi_PEgawai;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class koneksi {
private static Connection koneksi;
public static Connection getKoneksi()
{
//cek koneksi
if(koneksi == null)
{
try
{
String url;
url = "jdbc:mysql://localhost:3306/dbabsensipegawai";
String user = "root";
String password = "pk12basketboy";
line34 --> **DriverManager.registerDriver(new con.mysql.jdbc.Driver());**
koneksi = DriverManager.getConnection(url,user,password);
}catch(SQLException t)
{
JOptionPane.showMessageDialog(null, "Error Membuat Koneksi");
}
}
return koneksi;
}
static Object getConnection()
{
throw new UnsupportedOperationException("Not Yet Implemented");
}
}
You must have forgotten to add the database driver to the CLASSPATH. If you are under Eclipse, go to the Build path menu and add your driver, otherwise refer to the billion posts on the internet that explain how to add a class to the CLASSPATH for any system.