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

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();  

    }  


}  

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容