Java通过jdbc访问SQLServer数据库

1.在SQLServer新建数据库
数据库名JavaDB
表名Xyxx
这里写图片描述
2.修改sa账号的密码为123
安全性->登录名->sa->右键->属性
这里写图片描述
3.在 MyEclipse新建工程
第一步 File->New->Java Project->输入工程名->完成
标记图片3.1
第二步 在工程名上右键->New->Class->输入名字SQLHelper->完成
标记图片3.2
第三步 在工程名上右键->New->Other->MyEclipse->Swing->Matissee Form->Next->选择JFrame并输入名字->完成
标记图片3.3
4.在java工程导入sqljdbc4.jar包
sqljdbc4.jar(点击下载
右键->Build Path->Configure Build Path
这里写图片描述
这里写图片描述
5.SQLHelper.java文件

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class SQLHelper {
    private String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private String dbURL = "jdbc:sqlserver://127.0.0.1; DatabaseName=JavaDB";
    private String userName = "sa";
    private String userPasswd = "123";
    private Connection dbConn;
    private Statement stm = null;
    private int dbState = 0;
    public SQLHelper(){
        try {
            Class.forName(driverName);
            dbConn = DriverManager.getConnection(dbURL,userName, userPasswd);
            stm = dbConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public int getState(){
        return dbState;
    }
    public int ExecuteSQL(String sql){
        try {
            return stm.executeUpdate(sql);
        } catch (Exception e) {
            return -1;
        }
    }
    public ResultSet getRS(String sql){
         try {
            return stm.executeQuery(sql);
        } catch (Exception e) {
            return null;
        }
    }
    public Object[][] resultSetToObjectArray(ResultSet rs){
        Object[][] data = null;
        try {
            int rows = rs.getRow();
            data = new Object[rows][];
            ResultSetMetaData mdData = rs.getMetaData();
            int columnCount = mdData.getColumnCount();
            int k=0;
            while(rs.next()){
                System.out.println("i"+k);
                Object [] row = new Object[columnCount];
                for (int i=0; i<columnCount; i++){
                    row[i] = rs.getObject(i+1).toString();
                }
                data[k] = row;
                k++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        stm.close();
        stm = null;
        dbConn.close();
        dbConn = null;
    }

}

6.拖控件形成界面
注意事项:
这里写图片描述
这几个是处于一个JPanel上的
标记图片6.1
这是各个控件的命名,
这里写图片描述
7.编写初始化代码
标记图片7.1

private SQLHelper sqlHelper = null;
private int iSaveMethod = 0;
DefaultMutableTreeNode tnTop = null;

public myJDBCDBFrame() {
    initComponents();
    sqlHelper = new SQLHelper();
    tnTop = new DefaultMutableTreeNode("00_学院信息");
    tvXy.setModel(new DefaultTreeModel(tnTop));
    CreateTreeNode();
    plEdit.setEnabled(false);
    btnSave.setEnabled(false);
}

private void CreateTreeNode() {
    tnTop.removeAllChildren();
    ResultSet rsResultSet = sqlHelper
            .getRS("select * from tblXyxx order by Xydm ASC");
    try {
        while (rsResultSet.next()) {
            DefaultMutableTreeNode tnNode = new DefaultMutableTreeNode(
                    rsResultSet.getString("Xydm") + "_"
                            + rsResultSet.getString("Xymc"));
            tnTop.add(tnNode);
        }
        tvXy.updateUI();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

8.点击JTree执行的操作
在JTree上右键->Events->TreeSelection->valueChanged
标记图片8.1

String strSelected = tvXy.getSelectionPath().getLastPathComponent()
        .toString();
String xydm = strSelected.substring(0, 2);
try {
    Integer.parseInt(xydm);
} catch (Exception e) {
    return;
}
String xyName = strSelected.substring(3, strSelected.length());
txtID.setText(xydm);
txtName.setText(xyName);
plEdit.setEnabled(false);
btnSave.setEnabled(false);

9.编写保存按钮的功能
双击界面上的保存按钮,进入代码部分
标记图片9.1

String sSql = "";
String Xydm = txtID.getText();
if (Xydm.length() != 2) {
    JOptionPane.showMessageDialog(this, "请输入两位数字");
    return;
}
try {
    Integer.parseInt(Xydm);
} catch (Exception e) {
    JOptionPane.showMessageDialog(this, "请输入两位数字");
    return;
}
if (txtName.getText().trim().length() == 0) {
    JOptionPane.showMessageDialog(this, "请输入学院名称");
    return;
}
switch (iSaveMethod) {
case 1:
    // 添加数据
    sSql = "select * from tblXyxx where Xydm='" + Xydm + "'";
    try {
        ResultSet rs = sqlHelper.getRS(sSql);
        if (rs.next()) {
            JOptionPane.showMessageDialog(this, "编号已经存在");
            return;
        }
        sSql = "insert into tblXyxx(Xydm, Xymc) values('" + Xydm
                + "','" + txtName.getText().trim() + "')";
    } catch (Exception e) {
        e.printStackTrace();
    }
    break;
case 2:
    // 修改数据
    sSql = "update tblXyxx set Xymc='" + txtName.getText().trim()
            + "' where Xydm='" + Xydm + "'";
    break;
default:
    break;
}
if (sSql.length() != 0) {
    try {
        sqlHelper.ExecuteSQL(sSql);
        sqlHelper.ExecuteSQL(sSql);
        CreateTreeNode();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

10.取消 按钮的功能
标记图片10.1

txtID.setText("");
txtName.setText("");
plEdit.setEnabled(false);
btnSave.setEnabled(false);

11.添加 按钮的功能
标记图片11.1

iSaveMethod = 1;
txtID.setText("");
txtName.setText("");
plEdit.setEnabled(true);
btnSave.setEnabled(true);

12.编辑按钮的功能
标记图片12.1

iSaveMethod = 2;
plEdit.setEnabled(true);
btnSave.setEnabled(true);

13.删除按钮的功能
标记图片13.1

String Xydm = txtID.getText();
if (Xydm.length() == 0) {
    JOptionPane.showMessageDialog(this, "请选择要删除的数据");
    return;
}
if (JOptionPane.showConfirmDialog(this, "是否删除本信息", "信息提示",
        JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
    return;
}
String sSQL = "delete from tblXyxx where Xydm='" + Xydm + "'";
try {
    sqlHelper.ExecuteSQL(sSQL);
    CreateTreeNode();
    txtID.setText("");
    txtName.setText("");
} catch (Exception e) {
    e.printStackTrace();
}

14.完成验收
标记图片14.1
15.使用JTable显示数据库数据
新建一个form,参照第3步的第三步
标记图片15.1
16.编写代码
标记图片16.1

private ODBCHelper dblHelper;

public tableFrame() {
    initComponents();
    dblHelper = new ODBCHelper();
    BindTable();
}

private void BindTable() {
    try {
        Object[][] dataObjects = null;
        ResultSet rs = dblHelper.Query("select * from tblXyxx order by Xydm ASC");
        if (rs == null) {
            return;
        }
        if (!rs.last()) {
            return;
        }
        rs.last();
        int iCount = rs.getRow();
        dataObjects = new Object[iCount][2];
        if (rs.first()) {
            dataObjects[0][0] = rs.getString("Xydm");
            dataObjects[0][1] = rs.getString("Xymc");
        }
        int i = 1;
        while (rs.next()) {
            dataObjects[i][0] = rs.getString("Xydm");
            dataObjects[i++][1] = rs.getString("Xymc");
        }
        String[] columnTitle = { "学院代码", "学院名称" };
        tblXY.setModel(new DefaultTableModel(dataObjects, columnTitle));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

17.文件汇总
MyEclipse2 (2).rar(点击下载
MyJDBCDB.rar(点击下载

谢谢你看

 

<script>

var a_idx = 0;
jQuery(document).ready(function($) {
$("body").click(function(e) {
var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正" ,"法治", "爱国", "敬业", "诚信", "友善");
var $i = $("<span/>").text(a[a_idx]);
a_idx = (a_idx + 1) % a.length;
var x = e.pageX,
y = e.pageY;
$i.css({
"z-index": 999999999999999999999999999999999999999999999999999999999999999999999,
"top": y - 20,
"left": x,
"position": "absolute",
"font-weight": "bold",
"color": "#ff6651"
});
$("body").append($i);
$i.animate({
"top": y - 180,
"opacity": 0
},
1500,
function() {
$i.remove();
});
});
});

</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值