import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Test {
static Connection con = null;
static JFrame frame;
static JTable table;
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;
String[] header = { "Book ID", "Book Name" };
String[][] context = null;
int i = 0;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM books");
rs.last();
int nRecord = rs.getRow();
context = new String[nRecord+1][2];
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt("book_id");
String title = rs.getString("title");
context[i][0] = id + "";
context[i][1] = title;
System.out.println(id + " " + title);
i++;
}
} catch (SQLException e) {
e.printStackTrace();
}
table = new JTable(context, header);
JScrollPane scrollPane = new JScrollPane(table); // Make scrollpane with
// Add scrollpane with table to the frame and show the frame to user
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(600, 400);
frame.setVisible(true);
}
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) {
frame = new JFrame();
makeConnection();
selectAll();
//addBook("C++ Programming", "Freelec", "2011", 50000);
selectAll();
}
}
'실습과제 모음' 카테고리의 다른 글
JAVA Mysql + JTable + File (0) | 2012.07.29 |
---|---|
JAVA JFrame + MySql 추가 실습예제 (0) | 2012.07.28 |
JAVA Mysql 연결 실습 (0) | 2012.07.28 |
CPP 주말 과제 Time 클래스 (0) | 2012.07.27 |
CPP ImaginaryNumber (0) | 2012.07.27 |