how to insert data from textboxes into mysql database in java-netbeans - java

I am new to programming and i am trying to make an small Java swing application using netbeans IDE and i have designed the Form and created an table too i used the following code to insert data into database from the form but i am getting many errors please help me to correct this code:
import java.sql.*;
public class db
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
static final String USER="root";
static final String PASS="toor";
Connection conn = null;
Statement stmt = null;
static final String d_unit=jTextField2.getText();
static final String d_name=jTextField3.getText();
static final String d_dob=jDateChooser2.getText();
//static final String d_gender="gender";
static final String d_age=jTextField4.getText();
static final String d_doorno=jTextField5.getText();
static final String d_street=jTextField6.getText();
static final String d_vc=jTextField7.getText();
static final String d_district=jTextField8.getText();
static final String d_pin=jTextField9.getText();
static final String d_phone=jTextField10.getText();
static final String d_mail=jTextField11.getText();
static final String d_occupations=jTextField12.getText();
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) values('"+d_unit+"','"+d_name+"','"+d_dob+"','"+d_age+"','"+d_doorno+"','"+d_street+"','"+d_vc+"','"+d_district+"','"+d_pin+"','"+d_phone+"','"+d_mail+"','"+d_occupations+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e)
{ }
}

You may not use the final String because, then you can't modify these Strings, and the other code is correct, but i think you can use the ? in the line:
String sql="INSERT INTO ´donors´ (unit,name) VALUES (?,?)";
//put the rest of the sentence
try {
PreparedStatement pdt = cn.prepareStatement(sql);
pdt.setString(1, jTextField2.getText();
pdt.setString(2, jTextField3.getText();
//put the rest of the code
int n1=pdt.executeUpdate();
if(n1>0)
{
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
}catch (SQLException ex) { }
Well, that's the largest way, but the most correct. I hope this helps.

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
String itemCode = txtItemCode.getText();
String itemName = txtItemName.getText();
String unitPrice = txtUnitPrice.getText();
String qty = txtQty.getText();
String query = "insert into items values ('"+itemCode+"','"+itemName+"','"+unitPrice+"','"+qty+"')";
System.out.println(query);
try {
Connection c = DBClass.getConnection();
Statement stmt = c.createStatement();
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Saved");
} catch (Exception e) {
e.printStackTrace();
}
// DBClass
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* #author Nadun
*/
public class DBClass {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/stock", "root", "123");
}
return connection;
}
}

Everything looks alright. Maybe the trouble is on your mysql database?
Check the data type of your row in mysql, if your data type in the current row is "int", then it should be like this
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (name, age) values('"+d_name+"',,'"+Integer.valueOf(d_age.getText().toString())+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e){ }
}
You should be careful with data types. If your mysql row is int type then in your java you should give it int time as well.
I guess your data type of "name" row is text that use string, and your data type of "age" row is int?
I check your code is giving a string value from your java to your int mysql row. that's the error.
So you should convert the string to the int first
Integer.valueOf(d_age.getText().toString());

try proceeding like this for simplicity and less error-prone
String sql = "INSERT INTO donors(unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
stmt.executeUpdate(sql);

Related

My Java SQL Update statement is not updating my database, and I don't know if it's a problem with the statement or the connection

I am connecting my Java Program to a database stored in the program folder, and I am having users answer quiz questions and I want the results to be stored in the database. The Update statement is not working, and I don't know if it's a problem with the actual statement or the database connection.
I've tried creating a new database with the same tables and reconnecting to that database, but nothing seems to be working.
//database connection class
public class databaseConnection {
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager
.getConnection("jdbc:sqlite:D:\\Users\\mariammahmoud\\eclipse-workspace\\ia_2019_final\\testjava.db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
public class student {
public static final String DB_NAME = "testjava.db";
public static final String TABLE_STUDENTS = "students";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_GRADE = "grade";
public static final String COLUMN_RESULTS = "results";
public static final String COLUMN_EVENTS = "events";
public static final String COLUMN_USERNAME = "username";
public void main() {
try {
String user_name = login_student.sendQuiz();
Connection conn = databaseConnection.dbConnector();
ArrayList<String> results = new ArrayList<String>(15);
instructions();
questions(results);
results.trimToSize();
System.out.println("Here are the events that you should consider competing in:");
System.out.println(results);
String separator = ",";
int total = results.size() * separator.length();
for (String finalResults : results) {
total += finalResults.length();
}
StringBuilder sb = new StringBuilder(total);
for (String finalResults : results) {
sb.append(separator).append(finalResults);
}
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = " +user_name;
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Something went wrong:" + e.getMessage());
e.printStackTrace();
}
}
I expected the update statement to update the testjava.db database, but everything is staying the same. What should I do? Thank you in advance!
Your problem is that while you wisely used a prepared statement in your code for the update, you never actually used it for the username column in the WHERE clause. Hence, the query you are executing currently won't be interpreted as comparing some input against username. Rather, the username value will be interpreted as a column. Try this version:
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = ?";
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.setString(2, user_name);
myStmt.executeUpdate();
Note that you could have just tried the following:
String sql = "UPDATE students SET events = ? WHERE username = '" + user_name + "'";
But, please bind a value to a ? placeholder instead, as I have suggested above. One benefit of using statements is that it frees you from having to worry about how to escape your data in the query.

how to insert a variable in SQL which is already defined in the code

public class DB
{
public static void main(.....)
{ String str="hello";
....
st.executeUpdate("insert into r2( col1) values(.....)"); // here r2 is the table in which i want to insert the "str" defined above.
}}
i want to insert this 'str' in the table r2 using the insert command.
WHAT DO I WRITE HERE? TO INSERT VALUE OF "str" PREVIOUSLY DEFINED , how to pass the parameter 'str' from outside such that it gets inserted into the table??
You will write it like this .. assuming column name in table r2 is col1
public class DB
{
public static void main(.....)
{ String str="hello";
.... // Obtain DB Connection here
PreparedStatement ps = connection.prepareStatement("insert into r2( col1) values(?)";
ps.setString(1,str);
ps.execute();
}
}
The safest way is to use a Prepared Statement.
Here is Oracle's very comprehensive tutorial on using Prepared Statements.
In your case (assuming the column you want to insert the value into is named "world") it would be done something like this:
String str="hello";
Connection connection = [...] // Set up connection
String queryString = "insert into r2 ('world') values(?)";
Statement statement = connection.prepareStatement(queryString);
statement.setString(1, str);
statement.executeUpdate();
// Add exception handling, clean-up
Try it and see if it helps.
public class Example {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
PreparedStatement ps = conn.prepareStatement("insert into table_name( col1,col2,col3) values(?,?,?)";
ps.setString(1,str);
ps.setString(2,str);
ps.setString(3,str);
ps.execute();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

connecting Java to MySQL

I'm doing my dissertation on software engineering and im building a small application that makes use of a SQL DB, in this case MySQL. I'm also using the application controller pattern. So the code I have working for retrieving data from the db is;
public static void main(String[] args)
{
try
{
String url = "jdbc:mysql://localhost:3306/tm470_returns_stock_management_system";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"root","root");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM test_table");
while (res.next())
{
int id = res.getInt("test_id");
String msg = res.getString("test_info");
System.out.println(id + "\t" + msg);
}
con.close();
}
catch(Exception e)
{
System.out.println("DB connection unsuccesful");
}
}
I now want to transfer this out of my Main class/string and into my Application Controller Class (which is called Facility).
Now my question is, for every method in my Facility Class that needs to access the DB, do i have to do the full code each time? Or can i create a method within the Facility class that each application method can just call whenever it needs to access the DB. If i can condense all this into a method, can you advise me how to go about it please?
Be gentle with me guys, I am a learner :)
How about adding a utility class like ConnectionUtil and using the static method to access the connection.
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionUtil{
static final String url = "jdbc:mysql://localhost:3306/";
static final String dbName = "test";
static final String driver = "com.mysql.jdbc.Driver";
static final String userName = "userparatest";
static final String password = "userparatest";
Connection con = null;
static Connection getConnection() throws Exception {
if(con == null)
{ Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + dbName, userName,password);
}
return con;
}
}
this can be further improved but just providing a start..
just call below whenever you want a statement..
Statement st = ConnectionUtil.getConnection().createStatement();
I would map it as a own class, which is used by your application other classes. When you define it as a singleton you will only need one instance in your complete application
Yes , you can write a method for accessing db and you can reuse it across all the applications.
Keep the following in a method and reuse it.
String url = "jdbc:mysql://localhost:3306/tm470_returns_stock_management_system";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"root","root");
Statement st = con.createStatement();
int productID = 6;
String skuCode = "ABC123";
ResultSet res = st.executeQuery("SELECT * FROM test_table");
while (res.next())
{
int id = res.getInt("test_id");
String msg = res.getString("test_info");
System.out.println(id + "\t" + msg);
}

Why i can not connect to mysql db using java

I have used jdbc driver before.But for this piece of program i can't connect to the db.This doesn't throw any exception or anything. Just won't connect. I couldn't find a solution online either.Below is the code i tried to run :( Please help in solving this. Thank you in advance :)
public class HeapMySql<T extends Comparable<T>> implements HeapInterface {
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Heap";
static final String USERNAME = "root";
static final String PASSWORD = "";
private int size = 0 ;
String sql;
static Statement stmt = null;
static Connection conn = null;
static ResultSet rs = null;
public void HeapMySql(){
try
{
sql = "CREATE TABLE testHeap (index integer, value integer);";
stmt.executeUpdate(sql);
System.out.println("Done");
}catch(Exception e){
}
}
public static void main(String [] arg){
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database..."); //lets create a table in our database
stmt = conn.createStatement();
HeapMySql test1 = new HeapMySql<>();
}catch(ClassNotFoundException | SQLException ex){
}finally{
}
A constructor does not have a return type: docs
Remove void from public void HeapMySql() and it will do the work.
Also as said in comments, you should print the stacktrace in your catch blocks. This makes it easy to understand the exception and resolve the problem.

why can't java see my mysql driver

I'm having trouble working out why java can't see my mysql driver:
I've downloaded the driver .jar from the mysql website
I've added the jar to my runtime classpath
I can confirm the jar is on the classpath, by printing out the relevant system property
But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?
class example:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
My main class simply passes the query into the DB class:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}
You've a typo in the driver class name.
private String driverClassName = "com.myqsl.jdbc.Driver";
it should be
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?

Categories