· 9 years ago · Sep 17, 2017, 01:54 PM
1public class DbTesting
2{
3 public static void main(String[] args) throws FileNotFoundException, IOException
4 {
5 PreparedStatement ps=null;
6 Connection con;
7 try
8 {
9
10 Class.forName("com.mysql.jdbc.Driver");
11 con = DriverManager.getConnection("jdbc:mysql://localhost/", "root", ""); //no database is selected
12
13 ps=con.prepareStatement("CREATE DATABASE IF NOT EXISTS testpdf");
14 int Result=ps.executeUpdate(); // creating database if not exist
15
16 con = DriverManager.getConnection("jdbc:mysql://localhost/testpdf", "root", ""); // selecting databse
17 //selecting databse for statement
18
19 if(Result==0)
20 {
21 System.out.println("Databse Exist");
22 }
23 else if(Result==1)
24 {
25 System.out.println("Databse Created");
26 System.out.println("Creatiing Table. . . . .");
27
28 String user = "CREATE TABLE IF NOT EXISTS pdfCheck (\n"
29 + " FILE longblob Not Null);";
30
31 ps=con.prepareStatement(user);
32 ps.execute();
33 System.out.println("Table created");
34 }
35
36
37 File pdfFile = new File("C:\\Users\\Previn\\Desktop\\test.txt");
38 byte[] pdfData = new byte[(int) pdfFile.length()];
39 DataInputStream dis = new DataInputStream(new FileInputStream(pdfFile));
40 dis.readFully(pdfData); // read from file into byte[] array
41 dis.close();
42
43 String insert_maindb="INSERT INTO pdfCheck(File) values(?)";
44 ps=con.prepareStatement(insert_maindb);
45 ps.setBytes(1, pdfData);
46 ps.execute();
47
48
49
50 }
51 catch(ClassNotFoundException | SQLException e)
52 {
53 JOptionPane.showMessageDialog(null,e+"\n"+"Check your server connection");
54 }
55 }
56}