1 建立数据库,建表。
数据库:text表:fruit
2写db连接类
public class DBConMgr {
//private String driverName="oracle.jdbc.driver.OracleDriver";
private String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String userName="sa";
private String userPwd="sa123456";
private String url="jdbc:sqlserver://localhost:1433; DatabaseName=text";
public Connection conn=null;
public Statement sm=null;
public PreparedStatement psm=null;
public void ConnectDB(){
try {
Class.forName(driverName).newInstance();
conn=DriverManager.getConnection(url,userName,userPwd);
sm=conn.createStatement();
System.out.println("success");
} catch(Exception e) {
e.printStackTrace();
System.out.println("连接错误");
}
}
public void CloseDB(){
try {
if (sm != null) {
sm.close();
}
if(psm!=null)
{
psm.close();
}
conn.close();
} catch (SQLException SqlE) {
SqlE.printStackTrace();
System.out.println("-关闭错误");
}
}
3 画界面
我用的是myeclipse-swingfrom
4切换界面到Source
添加鼠标动作:
//确定,插入数据库
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String Name1 = new String(jTextField1.getText());
String Level1 = new String(jTextField2.getText());
DBConMgr db_conn = new DBConMgr();
db_conn.ConnectDB();
Connection conn = db_conn.conn;
//Statement stat = db_conn.sm;
//PreparedStatement psm =db_conn.psm;
// PreparedStatement psm =db_conn.psm;
try {
String sql = "insert into fruit(name,level) values(?,?)";
PreparedStatement psm = conn.prepareStatement(sql);
psm.setString(1, Name1);
psm.setString(2, Level1);
psm.executeUpdate();
JOptionPane.showMessageDialog(null, "数据已成功插入!");//弹出对话框
} catch (Exception ee) {
System.out.print("exception");
ee.printStackTrace();
}
}
//取消,清空
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText(" ");
jTextField2.setText(" ");
}
运行:
数据库: