import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
static Connection con = null;
static void makeConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("드라이버를 찾을 수 없습니다");
}
String url = "jdbc:mysql://localhost/book_db";
String user = "root";
String password = "green";
try {
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void selectAll() {
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM books");
while (rs.next()) {
int id = rs.getInt("book_id");
String title = rs.getString("title");
System.out.println(id + " " + title);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void addBook(String title, String publisher, String year,
int price) {
try {
Statement stmt = con.createStatement();
String s = "INSERT INTO books (title, publisher, year, price) VALUES ";
s += "('" + title + "','" + publisher + "','" + year + "','"
+ price + "')";
System.out.println(s);
int i = stmt.executeUpdate(s);
if (i == 1)
System.out.println("레코드 추가 성공");
else
System.out.println("레코드 추가 실패");
} catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
}
public static void main(String[] args) {
makeConnection();
selectAll();
addBook("C++ Programming", "Freelec", "2011", 50000);
selectAll();
}
}
'실습과제 모음' 카테고리의 다른 글
JAVA JFrame + MySql 추가 실습예제 (0) | 2012.07.28 |
---|---|
JAVA SQL + JFrame (0) | 2012.07.28 |
CPP 주말 과제 Time 클래스 (0) | 2012.07.27 |
CPP ImaginaryNumber (0) | 2012.07.27 |
CPP 표준체중 계산 프로그램 (0) | 2012.07.26 |