forked from rick2785/JavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaLesson34.java
More file actions
63 lines (40 loc) · 2.08 KB
/
JavaLesson34.java
File metadata and controls
63 lines (40 loc) · 2.08 KB
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
// The API for accessing and processing data stored in a database
import java.sql.*;
public class JavaLesson34 {
public static void main(String[] args) {
// A connection object is used to provide access to a database
Connection conn = null;
try {
// The driver allows you to query the database with Java
// forName dynamically loads the class for you
Class.forName("com.mysql.jdbc.Driver");
// DriverManager is used to handle a set of JDBC drivers
// getConnection establishes a connection to the database
// You must also pass the userid and password for the database
conn = DriverManager.getConnection("jdbc:mysql://localhost/customer","mysqladm","rickmoss");
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement sqlState = conn.createStatement();
// This is the query I'm sending to the database
String selectStuff = "Select first_name from customer";
// A ResultSet contains a table of data representing the
// results of the query. It can not be changed and can
// only be read in one direction
ResultSet rows = sqlState.executeQuery(selectStuff);
// next is used to iterate through the results of a query
while(rows.next()){
System.out.println(rows.getString("first_name"));
}
}
catch (SQLException ex) {
// String describing the error
System.out.println("SQLException: " + ex.getMessage());
// Vendor specific error code
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (ClassNotFoundException e) {
// Executes if the driver can't be found
e.printStackTrace();
}
}
}