I have a problem when I enter data from the application to mysql database, it appears in the form of "????" However, when I enter data via "phpmyadmin" the data appears normally
well the problem is when i enter data via application ,
not related with database
any way i tried to change the encode of database and the table and the fields inside the tables
here the insert query in my application
public static void dbConnect() {
try{
Class.forName(DRIVER);
connector = DriverManager.getConnection(DATA_BASE_BATH, "root", "");
insert = connector.prepareStatement("INSERT INTO students VALUES (?,?,?,?)");
}
public static void insert(int id , String name , String special , double gpa){
dbConnect();
try{
insert.setInt(1, id);
insert.setString(2, name);
insert.setString(3,special);
insert.setDouble(4,gpa);
insert.execute();
}
catch(SQLException e){
System.out.println(e.getMessage());
}
}
here the image to understand the problem
-the first row is the data entry from the application
-and the second row is the data entry manually from the phpmyadmin
Your application isn't properly handling the data.
You need to set the charset during the connection to the MySQL server.
Perhaps by running the command SET NAMES 'UTF8'; as part of your connection script.
This answer states that you can even make it part the JDBC connection string in DATA_BASE_BATH when referenced in your getConnection() function call, as does this one.
Related
I completed H2 database with few tables and I want to embed it to my application written in Intellij Community Edition. I tried to do this in two different ways but none of that works the way I want to.
First way with URL jdbc:h2:~/database but user home is different on every computer... The database works only on my pc.
Second way with URL jdbc:h2:./src/database and the database is inside the project indeed, connection works, but the tables appears to be empty even though while running H2 database engine (entering h2/bin/h2-version.jar) the tables contain data.
Why the database seems to be empty?
public static void main(String[] args) {
final String URL = "jdbc:h2:./src/database";
final String USER = "sa";
final String PASSWORD = "";
try {
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
System.out.println("Connected to H2!");
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("select * from table1");
while (resultset.next())
System.out.println(resultset.getString(1));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
and Ive got an exception:
Connected to H2!
Exception in thread "main" java.lang.RuntimeException: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "TABLE1" not found (this database is empty); SQL statement:
select * from table1 [42104-212]
at mainH2.main(mainH2.java:22)
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "TABLE1" not found (this database is empty); SQL statement:
select * from table1 [42104-212]
I am trying to access a database from a different server , but no success so far. The event is, when I choose the object "ALL" in my combobox, the table will load all data from different servers.
The current code, which I only connected to the localhost, works fine. However, when I try to connect another server to load both of their data, I get a syntax error when trying to put 192.168.1.51.sales.items in the String sqlall. Also, I tried modifying the prepareStatement by writing cn.prepareStatement(sqlall) + cn1.prepareSatement("union Select * from 192.168.1.52.sales.items); I have no more idea on how to connect on both servers.
I would like to apologize beforehand if you find my coding a bit messy. Thank you. My code is as follows:
private void combobox_branchItemStateChanged(java.awt.event.ItemEvent evt) {
Object branch = combobox_branch.getSelectedItem();
try
{
// All is selected
if("All".equals(branch))
{
Connection cn = db.itemconnector.getConnection();
String sqlall = " Select * from sales2.items union Select * from sales1.items union Select * from sales.items " ; //I tried accessing multiple databases in my own localhost and worked.
PreparedStatement ps = cn.prepareStatement(sqlall);
ResultSet rs = ps.executeQuery();
DefaultTableModel tm = (DefaultTableModel)itemTable.getModel();
tm.setRowCount(0);
while(rs.next())
{
Object o[] = {rs.getInt("id"), rs.getString("location"), rs.getString("product_name"),rs.getString("product_category"),rs.getString("product_description"),rs.getInt("product_stock"), rs.getFloat("product_price"), rs.getString("product_status")};
tm.addRow(o);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Connection Error", JOptionPane.ERROR_MESSAGE);
}
}
And I have a class in a different package and this is its code:
package db;
import java.sql.*;
public class itemconnector {
public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales","root","");
return cn;
}
It is not possible to query different databases on different servers in a single SQL query.
It is also not possible to get around this by "concatenating" prepared statements. (For a start, that is nonsensical Java!)
You need to open a separate Connection to each separate database server and query the relevant tables on that server. Then combine the information from the separate ResultSet objects in Java code.
The "combining" will be something like iterating the results in each result set and adding them to a Java data structure ...
I am trying and failing to send data from my java gui to my MS SQL database, I have dabbled with Java in the past but by no means am I an expert, I have been sourcing help from online and I have managed to connect my database to my application but i seem to be struggling with transferring data from the text fields to the database. (I am also new to stack so please put me straight in my place if I am out of line)
I have a class for my UI and a class for the database connection, the code is from a online resource and it seems straight forward and logical to follow (in my eyes) but I cannot seem to crack what should be a simple problem. The process is get the text from the text field and insert using a statement in to the SQL database, I can send data from within my code easily but I would ideally like it from the text fields.
The code cannot seem to see the "Connection" - error = java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: class Connection
I apologise in advance if this is a very simple mistake but it is driving me insane as it should be a fairly straight forward process. In plain terms it should be able to fill out the four text fields which fill the four columns in my DB when the submit button is pressed. Any help would be greatly appreciated.
this is the code for the action on my button:
private void SubmitBTNActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String number = Number.getText();
String title = Title.getText();
String year = Year.getText();
String query = "insert into students values ('"+Name+"','"+Number+"','"+Title+"','"Year+"')";
System.out.println(query);
try {
Connection c = DatabaseConnection.getConnection();
Statement stmt = c.createStatement();
stmt.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
}
this is the code in my database class
public class DatabaseConnection {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=*******;user=****;password=******;");
}
return connection;
}
}
Thanks
I'm trying to connect to a MySql database from a test-app in Java.
I have just followed a plain tutorial I found online. The code works (and compiles OK), but I cant log in to the db and fetch anything. Getting the error:
1:
Error connecting to DB: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user '******'#'%' to database '*****_javaapp'
java.lang.NullPointerException
Why does Java add the '#', and the '%' symbols in the console? Is that why I cant log in?
I am not able to modify priveliges on the db user. It's just set to "default" I guess by the ISP provider...
I have discussed this '#' & '%' issue with my friend, and I understand that these symbols are MySql syntax for "accept anything", but I still dont know what do to fix it as my MySql knowlede is limited..
If I modify some details in the db connection I sometimes get:
2:
Error connecting to DB: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
java.lang.NullPointerException
My code
My Main class:
package test;
import java.awt.EventQueue;
public class Main {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
// DB CONNECT
DBConnect connect = new DBConnect();
connect.getData();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
My connect class:
package test;
import java.sql.*;
public class DBConnect {
private Connection con;
private Statement st;
private ResultSet rs;
public DBConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://mywebhostadress:3306/some_db_name","some_db_user", "somepassword");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error connecting to DB: " + ex);
}
}
public void getData() {
try {
String query = "select * from Client";
rs = st.executeQuery(query);
System.out.println("Records from db: ");
while (rs.next()) {
String org_number = rs.getString("org_number");
String org_name = rs.getString("org_name");
System.out.println("org_number: " + org_number + "org_name: " + org_name);
}
} catch (Exception exgetData) {
System.out.println(exgetData);
}
}
}
Thanks for any helpfull tips!
UPDATE:
Hmmm…
In MySQL Workbench I manage to set up the connection OK… But I get the same error here:
“The account you are currently using does not have sufficient privileges to make changes to MySQL users and privileges.”
Also, while trying to forward engineer in MySQL Workbench:
ERROR 1044: Access denied for user 'some_db_user'#'%' to database 'new_schema'
SQL Statement:
CREATE SCHEMA new_schema
I have also tried to do it directly in phpMyAdmin, but there I can see this error on the front page:
“Create new database - No Privileges”
I have tried to grant my default (and only) user all the rights I can give, but it doesn’t get accepted when I do a query in phpMyAdmin.
I Guess this is why I can’t access it from my Java application. But I might type something wrong…
Shouldn’t it be:
GRANT ALL PRIVILEGES ON some_db_name.* TO 'some_db_user'#'%' WITH GRANT OPTION; ?
(taken from: this post)
I get:
Error
SQL query:
GRANT ALL PRIVILEGES ON some_db_name . * TO 'some_db_user '#'%' WITH GRANT OPTION
MySQL said:
1044 - Access denied for user 'some_db_user '#'%' to database ' some_db_name '
The error you're seeing:
Error connecting to DB:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
The last packet sent successfully to the server was 0 milliseconds
ago. The driver has not received any packets from the server.
java.lang.NullPointerException
is simply a connection error. Normally I'd suggest that you should try accessing your MySQL DB through the MySQL command line client or Workbench to check if it's up but here it like you haven't actually specified a host for the MySQL server (as you have a Null Pointer Error there).
You'll need to properly specify your host name in the form you provide in the OP. So to connect to a database called "some_db_name" on a local instance of MySQL as root (with the default blank password) you'd use:
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/some_db_name","root", "");
The #'%' part means the user can access from anywhere. Otherwise you can lock a user down a specific IP address or host name. It's possible to create a user role #% with lower privileges than one with the same user name but at a specific IP so then if that user logs in at that location they then get the roles of the specific IP. It has no relation to the error you're seeing here and it's what the default behaviour is for any added user unless they're specifically added with a host mask.
SOLVED! I finally found the sollution.
My hosting provider had changed the settings for the default user on their new platform. (I wasn't able to change it). I have done a lot of testing on several different platforms that the provider has to offer.
-In their new system, I wasn't able to do anything because the user didn't automatically have the right priviliges...
In their old system, I was able to accesss everything (since the user had "dba" (database admin) rights).
Thanks for all the input guys.
This is a small part of the application where user can register any number of employees and employee id is generated by using a while loop....As i close the application & start filling the data again in second round...the value of employee id empid resets to zero. Well, as long as the application is running, i get the desired o/p i.e. a unique id is allotted to every employee. I dont want empid's value to start from 0 whenever i start the application. Need alternatives and/or any modification. Code is provided here
int empcount=0;
public void actionPerformed(ActionEvent ae) {
//---------------------If user wants to add data
if(ae.getActionCommand()=="ADD EMPLOYEE") {
System.out.println("ADDING");
try{
empcount=empcount+1;//----------------will assign employees with unique emp id
//--------------------returns the text in name field to variables
String s_name=name.getText();
int s_code=empcount;
String s_dept=dept.getText();
String s_ph=ph.getText();
String s_bg=bg.getText();
String s_add=add.getText();
String s_date=date.getText();
PreparedStatement st=null;
Connection con = null;
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/", "SA", "");
st=con.prepareStatement("Insert into EmpReg (emp_name,emp_code,emp_ph,emp_bg,emp_add,emp_date,b_id) values(?,?,?,?,?,?,?)");
//---------------------parameters and respective values, passed to the SQL statement
st.setString(1,s_name);
st.setInt(2,s_code);
st.setString(3,s_ph);
st.setString(4,s_bg);
st.setString(5,s_add);
st.setString(6,s_date);
st.setString(7,s_dept);
st.execute();
JOptionPane.showMessageDialog(null,"Data is inserted into the database");
JOptionPane.showMessageDialog(code, "employee code"+ empcount+"");
con.close();
}
catch(Exception Ee){
System.out.println(Ee);
}
}
}
});
The standard SQL way of doing this, is having an "autoincrement" primary key (emp_code), for hsqldb see IDENTITY.
In the SQL INSERT statement leave out the primary key. Now the database generates a unique new key.
After the execution, you can retrieve the generated primary key from the statement with getGeneratedKeys.
This ensures that two parallel processes will not mess up the primary keys.
Why don't you create a field in your DB, that is set to autoIncrementTrue and maybe use it as ID as well. You can also use this field as Employee-Number.
You can check this Link for more Information: http://www.w3schools.com/sql/sql_autoincrement.asp
The generated number will increment every time you insert a new Employee.
You could use a DB like Oracle, MySQL, PostGre and use a Sequence or auto generated ID Column to do that for you