java链接到sql2008以及增删改查基本操作代码

package com.spring.test;
import java.sql.*;
class sqlServer {
    public static void main(String[] args) throws SQLException {
        Sql sql = new Sql();
        sql.Select();
//        sql.Insert("12s531","黄洪飞8302rw2");
        System.out.println();
//        sql.Delete("12sdf531");
        sql.UpDate("12sdf531", "2");
        sql.Select();
        sql.Close();
    }
}
class  Sql {
    Connection conn;
    Statement stmt;
    ResultSet rs;
    String url = "jdbc:sqlserver://localhost:1433;DatabaseName=XSCJ;";

    public Sql() throws SQLException {
        try {
            conn = DriverManager.getConnection(url, "sa", "sa");
            // 建立Statement对象
            stmt = conn.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
    }

    public void Select() throws SQLException {
        String sql = "select * from student";
        // 连接数据库
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            String Sno = rs.getString("Sno");
            String SName = rs.getString("Sname");
            System.out.println("Sno:" + Sno + "    SName" + SName);
        }
    }

    public void Insert(String Sno, String Sname) throws SQLException {
//        PreparedStatement preparedStatement=conn.prepareStatement(sql);
        String sql = "insert into Student(Sno,Sname)values(?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, Sno);
        preparedStatement.setString(2, Sname);
        preparedStatement.addBatch();
        preparedStatement.executeUpdate();
//        preparedStatement.close();
    }

    public void Delete(String Sno) throws SQLException {
        String sql = "delete from Student where Sno=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, Sno);
        preparedStatement.executeUpdate();
    }

    public void UpDate(String Sno, String SName) throws SQLException {
        String sql = "update Student set  Sname=? where Sno=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, SName);
        preparedStatement.setString(2, Sno);
        preparedStatement.executeUpdate();
    }

    public void Close() throws SQLException {
        stmt.close();
        conn.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值