Inserting data from Java GUI text field to MS SQL database - java

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

Related

dynamically populating a combobox with database data issue

I'm trying to populate my combo box with incremental ID's from my ms access database, when I run my program the program runs fine although there is no data inside the combo box and no error given from the console. Can anyone have a look through my code to see how I'm going wrong?
private JComboBox comboBox;
Connection con;
PreparedStatement pst;
ResultSet vResults;
Statement vStatement;
void updatecombo() throws SQLException {
try {
con = connectionz.getConnection();
vStatement = con.createStatement();
String vQuery = "SELECT Book_ID FROM books";
vResults = vStatement.executeQuery(vQuery);
while(vResults.next()) {
comboBox.addItem(vResults.getString("Book_ID"));
}
} catch (Exception e) {
}
}
Database
empty list
If "Book_ID" is really a string and not a numeric, problem might be with connection. If no errors exist, it might be connected to duplicate server with no data in it.
vResults.get**String**("Book_ID")
The issue was, I wasn't initialising the combo box correctly. Thanks for the comments I was completely overlooking that I wasn't printing the exception and getting to caught up in the SQL.

arabic data problem when it inserts from the java application (mysql , javafx)

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.

How to get text from textField in swing and put that text in a query

I tried getting the text into a string variable using the getText() method and then using that string variable in the preparedStatement of JDBC.
The application runs without any hiccups but gives a blank output.
Connection conn;
try{
conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
PreparedStatement pstmt=conn.prepareStatement("SELECT * FROM airplane.airlinedb WHERE
ORIGIN = ? AND DESTINATION = ? LIMIT 100;");
pstmt.setString(1,j.from); // from is the string variable
pstmt.setString(2,j.destination); //destination is another string variable
ResultSet rs=pstmt.executeQuery();
User user;
while(rs.next())
{
user = new User(rs.getString("ORIGIN"),
rs.getString("DESTINATION"),rs.getInt("FLIGHT_NUMBER"), rs.getInt("TIME_TRAVEL") ,
rs.getInt("PRICE"));
usersList.add(user);
}
conn.close();
}
catch(SQLException e){
System.err.println(e);
}
return usersList;
}
Please do let me know if u need any additional info
P.S:- this is my first java application so have been thru a lot of hiccups
this is the front end of the application..
i am trying to get the text from source and destiantion text field and use that into the different queries for the different options ..
Front End
adding the screenshot of the blank outputFinal Output

How to access a database from a specific server using Java?

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 ...

INSERT SQL in Java

I have a Java application and I want to use SQL database. I have a class for my connection :
public class SQLConnection{
private static String url = "jdbc:postgresql://localhost:5432/table";
private static String user = "postgres";
private static String passwd = "toto";
private static Connection connect;
public static Connection getInstance(){
if(connect == null){
try {
connect = DriverManager.getConnection(url, user, passwd);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Connection Error", JOptionPane.ERROR_MESSAGE);
}
}
return connect;
}
}
And now, in another class I succeeded to print my values but when I attempt to insert a value nothing is happening ...
Here's my code :
try {
Statement state = SQLConnection.getInstance().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
Statement state2 = SQLConnection.getInstance().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
state2.executeUpdate("INSERT INTO table(field1) VALUES (\"Value\")"); // Here's my problem
ResultSet res = state.executeQuery("SELECT * FROM table");
You need to commit (and close) the connection (and statement) after use. You also need to ensure that you aren't swallowing any SQLExceptions which may cause that you see "nothing" to happen.
That said,
private static Connection connect;
This is a terribly bad idea. You should never declare external resources as static in your application. Your application will break when the other side decides to close the resource because it's been released for a too long time. You really need to acquire and close those resources (Connection, Statement and ResultSet in the shortest possible scope. I.e. inside the very same method block as where the query is to be executed.
Also, I strongly recommend to use PreparedStatement instead of Statement since that will prevent your code from SQL injection attacks.
You may find this article useful to learn more about how to do basic JDBC interaction the right way.
state2.executeUpdate("INSERT INTO table(field1) VALUES (\"Value\")");
should be:
state2.executeUpdate("INSERT INTO plateau(field1) VALUES (\"Value\")");
Copuld just be a copy over to SO error, but looking but shoulding INSERT INTO table(field1) be INSERT INTO plateau(field1)?

Categories

Resources