Created with IntelliJ IDEA User hunter Date 31 03 15 Time 22 22 To cha

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Created with IntelliJ IDEA.
* User: hunter
* Date: 31.03.15
* Time: 22:22
* To change this template use File | Settings | File Templates.
*/
import java.sql.*;
public class Client {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/hunter";
static final String USER = "hunter";
static final String PASS = "123456";
public static void main(String s[]) {
Connection conn = null;
PreparedStatement parametersInsert;
PreparedStatement parametersUpdate;
PreparedStatement parametersDelete;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
// CONNECTION
conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmtDrop = conn.createStatement();
stmtDrop.executeUpdate("DROP TABLE if exists Person");
// CREATE
Statement stmtCreate = conn.createStatement();
String commandCreate = "CREATE TABLE Person ( " +
" id int unsigned NOT NULL AUTO_INCREMENT, " +
" name VARCHAR(50) NOT NULL, " +
" telephone VARCHAR(50) NOT NULL," +
" PRIMARY KEY(id) " +
") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT = 1; ";
stmtCreate.executeUpdate(commandCreate);
// INSERT
Statement stmtInsert = conn.createStatement();
String name = "Tolya";
String phone = "0993812832";
parametersInsert = conn.prepareStatement("INSERT INTO Person(name,telephone) VALUES (?, ?)");
parametersInsert.setString(1, name);
parametersInsert.setString(2, phone);
parametersInsert.executeUpdate();
// UPDATE
Statement stmtUpdate = conn.createStatement();
String newName = "NewTolya";
parametersUpdate = conn.prepareStatement("UPDATE Person SET name = ? WHERE name= ?");
parametersUpdate.setString(1, newName);
parametersUpdate.setString(2, name);
parametersUpdate.executeUpdate();
// SELECT
Statement stmtSelect = conn.createStatement();
ResultSet rs = stmtSelect.executeQuery("SELECT name, telephone FROM Person");
while(rs.next()){
System.out.println(" name: " + rs.getString("name"));
System.out.println(" telephone: " + rs.getString("telephone"));
}
// DELETE
parametersDelete = conn.prepareStatement("DELETE FROM Person WHERE telephone = ? ");
parametersDelete.setString(1, "0993812832");
parametersDelete.execute();
// DROP TABLE
stmtDrop.executeUpdate("DROP TABLE if exists Person");
} catch (Exception ex) {
System.out.println("Exception : " + ex.getMessage());
}
System.out.println("-_-");
}
}