· 10 years ago · Aug 03, 2016, 11:54 AM
1import java.sql.*;
2
3public class MainApp
4{
5 public static void main(String[] args)
6 {
7
8 /**
9 * 3306 is the default port for MySQL in XAMPP. Note both the
10 * MySQL server and Apache must be running.
11 */
12 String url = "jdbc:mysql://localhost:3306/";
13
14 /**
15 * The MySQL user.
16 */
17 String user = "root";
18
19 /**
20 * Password for the above MySQL user. If no password has been
21 * set (as is the default for the root user in XAMPP's MySQL),
22 * an empty string can be used.
23 */
24 String password = "";
25
26 try
27 {
28 Class.forName("com.mysql.jdbc.Driver").newInstance();
29 Connection con = DriverManager.getConnection(url, user, password);
30
31 Statement stt = con.createStatement();
32
33 /**
34 * Create and select a database for use.
35 */
36 stt.execute("CREATE DATABASE IF NOT EXISTS test");
37 stt.execute("USE test");
38
39 /**
40 * Create an example table
41 */
42 stt.execute("DROP TABLE IF EXISTS people");
43 stt.execute("CREATE TABLE people (" +
44 "id BIGINT NOT NULL AUTO_INCREMENT,"
45 + "fname VARCHAR(25),"
46 + "lname VARCHAR(25),"
47 + "PRIMARY KEY(id)"
48 + ")");
49
50 /**
51 * Add entries to the example table
52 */
53 stt.execute("INSERT INTO people (fname, lname) VALUES" +
54 "('Joe', 'Bloggs'), ('Mary', 'Bloggs'), ('Jill', 'Hill')");
55
56 /**
57 * Query people entries with the lname 'Bloggs'
58 */
59 ResultSet res = stt.executeQuery("SELECT * FROM people WHERE lname = 'Bloggs'");
60
61 /**
62 * Iterate over the result set from the above query
63 */
64 while (res.next())
65 {
66 System.out.println(res.getString("fname") + " " + res.getString("lname"));
67 }
68 System.out.println("");
69
70 /**
71 * Same as the last query, but using a prepared statement.
72 * Prepared statements should be used when building query strings
73 * from user input as they protect against SQL injections
74 */
75 PreparedStatement prep = con.prepareStatement("SELECT * FROM people WHERE lname = ?");
76 prep.setString(1, "Bloggs");
77
78 res = prep.executeQuery();
79 while (res.next())
80 {
81 System.out.println(res.getString("fname") + " " + res.getString("lname"));
82 }
83
84 /**
85 * Free all opened resources
86 */
87 res.close();
88 stt.close();
89 prep.close();
90 con.close();
91
92 }
93 catch (Exception e)
94 {
95 e.printStackTrace();
96 }
97 }
98}