美文网首页
java操作数据的插入,修改与删除

java操作数据的插入,修改与删除

作者: 喵大树 | 来源:发表于2018-01-04 19:00 被阅读0次

    import java.sql.Connection;  

    import java.sql.DriverManager;  

    import java.sql.ResultSet;  

    import java.sql.SQLException;  

    import java.sql.Statement;  

    public class JDBCTest {  

    // 定义数据库访问参数  

    String url ="jdbc:sqlserver://localhost:1433; DatabaseName=lihongchao";  

    String user ="sa";  

    String password ="a123456";  

    static String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";  

         Connection conn;  

         Statement st;  

    // 1、加载驱动  

    static {  

    try {  

                Class.forName(driverName);  

    }catch (ClassNotFoundException e) {  

    System.out.println("驱动加载失败");  

            }  

        }  

    // 2、创建连接对象  

    public  Connection getConnection() throws SQLException{  

            conn=DriverManager.getConnection(url,user,password);  

    return conn;  

        }  

    public  void add() throws ClassNotFoundException, SQLException {  

    // 定义sql语句  

    String sql1="insert into Table2(id,name,grade) values('20121114','大学英语',3)";  

    String sql2="insert into Table2(id,name,grade) values('20121115','体育',2)";  

    String sql3="insert into Table2(id,name,grade) values('20121116','马克思',3)";  

    // 3、创建语句对象  

        st =getConnection().createStatement();  

    // st.executeUpdate(sql1);  

        st.executeUpdate(sql2);  

        st.executeUpdate(sql3);  

    // 4、遍历结果集:此处插入记录不需要  

    // 5、关闭资源对象  

         st.close();  

         getConnection().close();  

    }  

    public  void update() throws ClassNotFoundException, SQLException {  

    // 定义sql语句  

    String sql1="update Table2 set grade=1  where grade=2";  

    // 3、创建语句对象  

            st =getConnection().createStatement();  

            st.executeUpdate(sql1);  

    // 4、遍历结果集:此处插入记录不需要  

    // 5、关闭资源对象  

             st.close();  

             getConnection().close();  

        }  

    public  void delete() throws ClassNotFoundException, SQLException {  

    // 定义sql语句  

    String sql1="delete Table2 where id='20121115'";  

    String sql2="delete Table2 where id='20121116'";  

    // 3、创建语句对象  

            st =getConnection().createStatement();  

            st.executeUpdate(sql1);  

            st.executeUpdate(sql2);  

    // 4、遍历结果集:此处插入记录不需要  

    // 5、关闭资源对象  

             st.close();  

             getConnection().close();  

        }  

    public static void main(String[] args) throws ClassNotFoundException,SQLException {  

    JDBCTest jt=new JDBCTest();  

        jt.add();  

        jt.update();  

        jt.delete();  

        }  

    }  

    相关文章

      网友评论

          本文标题:java操作数据的插入,修改与删除

          本文链接:https://www.haomeiwen.com/subject/kdhdnxtx.html