How to input data into a MySQL Data Base table using java
ExamplePackage = Test2
Class = DB
Data Base = studentinfo
Table Name = bank
package Test2;
import java.sql.*;
class DB {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "");
String sql = "insert into bank "
+ " (Account_No, Customer_Name, Intrest_Rate, Current_Balance)" + " values (?, ?, ?, ?)";
PreparedStatement stmt=con.prepareStatement(sql);
stmt.setString(1, "123456");
stmt.setString(2, "Pamitha");
stmt.setInt(3, 10);
stmt.setInt(4, 1000);
stmt.executeUpdate();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Sketch
Copy the following java codes and replace data printed in green. Then run the java program
package Package Name;
import java.sql.*;
class Class Name {
public
static void main(String args[]) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Data Base Name", "root",
"");
String
sql = "insert into Table Name "
+
" (Field 1, Field2, Field3,Field4)"
+ " values (?, ?, ?, ?)";
PreparedStatement
stmt=con.prepareStatement(sql);
stmt.setString(1,
"Data to Field1");
stmt.setString(2,
" Data to Field2");
stmt.setInt(3,
Data to Field3);
stmt.setInt(4,
Data to Field4);
stmt.executeUpdate();
con.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
No comments:
Post a Comment