Java Netbeans MySql database Connection - java

I want to insert row into MySql database with a normal Program for Mysql connection in Java Netbeans,but when i run this code my database remains unaffected.I had setup connection with Netbeans and Mysql and it is working fine.
Code:
import java.sql.*;
public class MySqlConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/migration";
static final String USER = "root";
static final String PASS = "ngts12345";
public static void main(String[] args) {
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO document (document_id, document_name, format)" +
"VALUES (?, ?, ?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
preparedStatement.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
}catch(Exception e){
//Handle errors for Class.forName
}
}
}

there is not space after format) and values
Change this line to
String sql = "INSERT INTO document (document_id, document_name, format)" +
"VALUES (?, ?, ?)";
to
String sql = "INSERT INTO document(document_id, document_name, format) " +
"VALUES (?, ?, ?)";

Try doing this:
preparedStatement.executeUpdate(sql);
and you should also specify database
String sql = "INSERT INTO database_name.document (document_id, document_name, format)" +"VALUES (?, ?, ?)";

try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","");
String sql = "select * from 'table_name'.database_name where user=? and pass=?";
pst = conn.prepareStatement(sql);
rs= pst.executeQuery();
}

Note preparedStatement.executeUpdate() returns true (record was successful in insert, update, or delete) or false (not successful). Therefore I suggest printing out the result to see if it worked.
As for not getting an error message, are you consuming exceptions and not printing out the error? In your catch block, put e.printStackTrace() to see what the error is.

Related

Parameter index out of range ( 2 number of parameters,which is 1)

I got this problem in my code java.sql.Exception: Parameter index out of range ( 2 number of parameters,which is 1).
This is my code:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t201835006","root","p73421231");
String mysql = "insert into books (bookName,Author,Perinting,Available) VALUES ('?','?',?,'True')";
PreparedStatement pstmt = conn.prepareStatement(mysql);
pstmt.setString(1,jTextField1.getText());
pstmt.setString(2,jTextField2.getText());
pstmt.setInt(3,Integer.parseInt(jTextField3.getText()));
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"insertion successful");
I tried :
"insert into books VALUES ('?','?',?,'True')";
"insert into books VALUES (?,?,?,'True')";
but it didn'T work.
My other codes in same project includes same databases but it works. I want to share iw for you:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t201835006","root","p73421231");
String sql ="insert into customerinfo values (?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,jTextField3.getText());
pstmt.setString(2,jTextField1.getText());
pstmt.setInt(3,Integer.parseInt(jTextField2.getText()));
pstmt.setString(4,jTextField4.getText());
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"insertion successful");
new Menu().setVisible(true);
dispose();
I don't know why the first code doesn't work help me.

Java String insertion to MySQL field of type MEDIUMTEXT

I'm taking a string and inserting it into a mySQL database field of type MEDIUMTEXT. When I print it out, there is a bunch of '-' characters and whitespace surrounding a slightly corrupted version of my original text. Am I doing this wrong?
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tripDB?characterEncoding=utf8","root","pass");
Statement stmt = con.createStatement();
query = "insert into trip (name, date, details) values (?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1, name); //Inserts correctly (varchar)
preparedStmt.setString(2, date); //Correct (varchar)
preparedStmt.setString(3, details); //Corrupted (MEDIUMTEXT)
preparedStmt.execute();
con.close();

Insert multiple data (List) in MySQL using JDBC

I am trying it from last 2 hour i dont know what is going wrong. also let me know how could i test if the connection is successfull or not.. it is for now.. but still i wanted to know..
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?)'
My code:
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/medicinedb";
static final String USER = "root";
static final String PASS = "";
static final String DRIVER = "com.mysql.jdbc.Driver";
public boolean saveMedicine(List<MedicineName> medicineName) throws ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(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...");
stmt = conn.createStatement();
for (MedicineName element : medicineName) {
String sql;
sql = " insert into medicinename (name, pgurl)" + " values
( ?, ?)";
System.out.println(conn);
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
stmt.executeUpdate(sql);
}
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
Why you are using Statement and Prepared statement. You are performing operations with Statement. Thus it does not have value. Remove the Statement
stmt = conn.createStatement();
And do the following
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
//stmt.executeUpdate(sql);
preparedStmt .executeUpdate(sql);
use
String sql = "insert into medicinename (name, pgurl) values (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString (1, element.getName());
preparedStmt.setString (2, element.getPgurl());
preparedStmt.executeUpdate();
you should delete executeUpdate(sql); to executeUpdate();
You mix between your stm and preparedStmt, you have to execute preparedStmt and not stm.
Another thing when you want to executing multiple statements as one unit, its good to work with Statement Batching instead for example :
PreparedStatement preparedStmt;
String sql;
conn.setAutoCommit(false);
for (MedicineName element : medicineName) {
sql = "insert into medicinename (name, pgurl) values (?, ?)";
System.out.println(conn);
preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
preparedStmt.addBatch(sql);
}
preparedStmt.executeBatch();
conn.commit();

how insert value into sql sever using java?

sorry if my questions are identical. I was trying to find out online documentation but I still have not solved the problem. it's an error in the line "stmt.executeUpdate ();"
public class DBConnect {
private List<SinhVien> result = new ArrayList<SinhVien>();
public void updateSQL(String masv, String malop, String ten,
Date ngaysinh, String diachi) {
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://MyPC:1433;databasename=QLSV;username=sa;password=APASSWORD");
PreparedStatement stmt = connection.prepareStatement("INSERT INTO SinhVien(masv, malop, ten, ngaysinh, diachi) VALUES(?, ?, ?, ?, ?");
stmt.setString(1, masv);
stmt.setString(2, malop);
stmt.setString(3, ten);
stmt.setDate(4, ngaysinh);
stmt.setString(5, diachi);
stmt.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
DBConnect dbConnect = new DBConnect();
dbConnect.XuatDSSV();
dbConnect.findSinhvienById("51003146");
dbConnect.updateSQL("123", "malop", "ten", null, "diachi");
}
I suggest you store your query in a String. It would have been easier to read, and find the problem...
final String query = "INSERT INTO SinhVien"
+ "(masv, malop, ten, ngaysinh, diachi) "
+ "VALUES(?, ?, ?, ?, ?)"; // <-- You were missing the close paren.
PreparedStatement stmt = connection.prepareStatement(query);
Try to add connection.commit() after stmt.executeUpdate(). And please, post the exception.

Inserting variable values into SQL Server using Java

So far I have been able to insert data into my SQL table only when i declare values inside the executedUpdate statement. What I wanted to know if there is a way that I can pass those values as variables that I will declare as parameters in the executing method like so:
public void updateSQL(String name, String dnsName, String ipV4, String ipV6, int statusCode)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://servername;database=databasename;integratedSecurity=true");
System.out.println("Database Name: " + connection.getMetaData().getDatabaseProductName());
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID)" + "VALUES(#Name, #DNSName, #IPAddressV4, #IPAddressV6, #StatusCodeID)");
System.out.println("Data Inserted");
ResultSet resultSet = statement.executeQuery("SELECT Name FROM ComputerStatus");
while(resultSet.next())
{
System.out.println("Computer Name: " + resultSet.getString("Name"));
}
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
System.err.println("Problem Connecting!");
}
}
I've tried couple of different things but no luck so far. Anyone know if this can be done?
You may use PreparedStatement instead of Statement.
PreparedStatement stmt = connection.prepareStatement("insert into test (firstname, lastname) values (?, ?");
stmt.setString(1, name);
stmt.setString(2, lname);
stmt.executeUpdate();
Using this way, you prevent SQL injection.
Have a look here :
PreparedStatement prep = conn.prepareStatement("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID) VALUES(?, ?, ?, ?, ?)");
prep.setString(1, name);
prep.setString(2, dnsName);
prep.setString(3, ipV4name);
prep.setString(4, ipV6);
prep.setInt(5, statusCode);
prep.executeUpdate();
this will help you understand.

Categories