怎样编写一个java程序能通过jdbc访问数据库实现对数据库的插入、删除、修改和查询?

怎样编写一个java程序能通过jdbc访问数据库实现对数据库的插入、删除、修改和查询?,第1张

1.增加\x0d\x0aString s1="insert into tableNames (id,name,password) values(myseq.nextval,?,?)"\x0d\x0aClass.forName(driver)\x0d\x0aConnection conn = DriverManager.getConnection(url,dbUser,dbPwd)\x0d\x0aPreparedStatement prepStmt = conn.prepareStatement(s1)\x0d\x0aprepStmt.setString(1,name)\x0d\x0aprepStmt.setString(2,password)\x0d\x0aResultSet rs=stmt.executeUpdate()\x0d\x0a2、删除\x0d\x0aString s2="delete from tbNames where name=?"\x0d\x0aClass.forName(driver)\x0d\x0aConnection conn = DriverManager.getConnection(url,dbUser,dbPwd)\x0d\x0aPreparedStatement prepStmt = conn.prepareStatement(s2)\x0d\x0aprepStmt.setString(1,name)\x0d\x0aResultSet rs=stmt.executeUpdate()\x0d\x0a3、修改\x0d\x0aString s3=“update tbNames set name=? where id=?”\x0d\x0aClass.forName(driver)\x0d\x0aConnection conn = DriverManager.getConnection(url,dbUser,dbPwd)\x0d\x0aPreparedStatement prepStmt = conn.prepareStatement(s3)\x0d\x0aprepStmt.setString(1,name)\x0d\x0aprepStmt.setString(2,id)\x0d\x0aResultSet rs=stmt.executeUpdate()\x0d\x0a4、查询\x0d\x0aString s4="select id,name,password from tbNames"\x0d\x0aClass.forName(driver)\x0d\x0aConnection conn = DriverManager.getConnection(url,dbUser,dbPwd)\x0d\x0aStatement stmt=conn.createStatement()\x0d\x0aResultSet rs = stmt.executeQuery(s4)\x0d\x0awhile(rs.next){\x0d\x0aint id=rs.getInt(1)\x0d\x0aString name = rs.getString(2)\x0d\x0aString pwd=rs.getString(3)\x0d\x0aSystem.out.println(id+name+pwd)} \x0d\x0a\x0d\x0a以上四步必须都得关闭连接;!!!\x0d\x0ars.close()\x0d\x0astmt.close()\x0d\x0aconn.close()

我这有个类,一直用

package com.second.dao

import java.lang.reflect.InvocationTargetException

import java.lang.reflect.Method

import java.sql.Connection

import java.sql.DriverManager

import java.sql.PreparedStatement

import java.sql.ResultSet

import java.sql.ResultSetMetaData

import java.sql.SQLException

import java.util.ArrayList

import java.util.List

public class JDBCUtilDao {

    private static Connection con = null

    private static PreparedStatement ps = null

    private static ResultSet rs = null

    public static Connection PrintCon() {

        return con

    }

    public static PreparedStatement PrintPs() {

        return ps

    }

    public static ResultSet PrintRs() {

        return rs

    }

    /**

     * 准备驱动

     */

    static {

        try {

            Class.forName("net.sourceforge.jtds.jdbc.Driver")

        } catch (ClassNotFoundException e) {

            // TODO Auto-generated catch block

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

            e.printStackTrace()

        }

    }

    public static Connection getConnection() {

        try {

            con = DriverManager.getConnection(

                    "jdbc:jtds:sqlserver://192.168.6.110/sql_second", "sa",

                    "123")

            // System.out.println(con)

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            System.out.println("连接失败!")

            e.printStackTrace()

        }

        return con

    }

    /**

     * 关闭连接

     * 

     * @param rs

     *            结果集对象

     * @param ps

     *            会话对象

     * @param con

     *            连接对象

     */

    public static void closeAll(ResultSet rs, PreparedStatement ps,

            Connection con) {

        try {

            if (null != rs) {

                rs.close()

            }

            if (null != ps) {

                ps.close()

            }

            if (null != con) {

                con.close()

            }

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace()

        }

    }

    /**

     * 设置参数

     * 

     * @param params

     * @param ps

     */

    public static void setParams(List<String> params, PreparedStatement ps) {

        if (params != null) {

            for (int i = 0 i < params.size() i++) {

                try {

                    ps.setString(i + 1, params.get(i))

                } catch (SQLException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace()

                }

            }

        }

    }

    /**

     * 实现增、删、改

     * 

     * @param sql

     *            sql语句

     * @param params

     *            参数

     * @return 修改的行数

     */

    public static int doUpdata(String sql, List<String> params) {

        int result = 0

        try {

            // 判断是否连接 不连接就把数据库连上

            if (null == con || con.isClosed()) {

                con = getConnection()

            }

            // 得到会话

            ps = con.prepareStatement(sql)

            // 设置参数

            setParams(params, ps)

            // 得到结果,即改变行数

            result = ps.executeUpdate()

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace()

        } finally {

            closeAll(null, ps, con)

        }

        return result

    }

    /**

     * 查询

     * 

     * @param <T>

     * @param sql

     * @param params

     * @param t

     * @return

     */

    public static <T> List<T> qureyAll(String sql, List<String> params,

            Class<T> t) {

        // 用一个集合接受返回的数据

        List<T> list = new ArrayList<T>()

        // 判断是否连接

        try {

            if (null == con || con.isClosed()) {

                con = getConnection()

            }

            //  *** 作对象

            ps = con.prepareStatement(sql)

            // 设置参数

            setParams(params, ps)

            // 返回结果集

            rs = ps.executeQuery()

            // 取出t中的说有方法

            Method[] method = t.getDeclaredMethods()

            // 取出说有列名和列数

            ResultSetMetaData rsmd = rs.getMetaData()

            // 获得列数

            int count = rsmd.getColumnCount()

            // 取出每个列列名放入数组中

            String[] columns = new String[count]

            for (int i = 0 i < columns.length i++) {

                columns[i] = rsmd.getColumnName(i + 1)

            }

            // 循环结果集

            while (rs.next()) {

                T s = (T) t.newInstance()

                // 第一个循环控制列数

                for (int i = 0 i < columns.length i++) {

                    // 第二个循环控制方法名

                    for (int j = 0 j < method.length j++) {

                        String setName = "set" + columns[i]

                        if (setName.equalsIgnoreCase(method[j].getName())) {// set+列名相同就是这个类得方法名

                            String typeName = rsmd.getColumnTypeName(i + 1)// 得到数据库中列名的类型

                            // int

                            // varchar..

                            //System.out.println(typeName)

                            if (typeName.equals("INTEGER")

                                    || typeName.equals("int identity")

                                    || typeName.equals("int")) {

                                method[j].invoke(s, rs.getInt(columns[i]))

                            } else if (typeName.equals("DECIMAL")) {

                                method[j].invoke(s, rs.getDouble(columns[i]))

                            } else if (typeName.equals("VARCHAR2")) {

                                method[j].invoke(s, rs.getString(columns[i]))

                            } else if (typeName.equals("money")) {

                                method[j].invoke(s, rs.getFloat(columns[i]))

                            } else if (typeName.equals("datetime")) {

                                // System.out.println(rs.getTimestamp(columns[i]))

                                method[j]

                                        .invoke(s, rs.getTimestamp(columns[i]))

                            } else {

                                method[j].invoke(s, rs.getString(columns[i]))

                            }

                        }

                    }

                }

                list.add(s)

            }

            closeAll(rs, ps, con)

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace()

        } catch (InstantiationException e) {

            // TODO Auto-generated catch block

            e.printStackTrace()

        } catch (IllegalAccessException e) {

            // TODO Auto-generated catch block

            e.printStackTrace()

        } catch (IllegalArgumentException e) {

            // TODO Auto-generated catch block

            e.printStackTrace()

        } catch (InvocationTargetException e) {

            // TODO Auto-generated catch block

            e.printStackTrace()

        }

        return list

    }

    /**

     * 查询

     * 

     * @param sql

     * @param obj

     * @return

     */

    public static ResultSet getInfoos(String sql, Object[] temp) {

        ResultSet rs = null

        try {

            if (con == null || con.isClosed()) {

                getConnection()

            }

            ps = con.prepareStatement(sql)

            for (int i = 1 i < temp.length i++) {

                ps.setObject(i, temp[i])

            }

            rs = ps.executeQuery()

        } catch (SQLException e) {

            e.printStackTrace()

        }

        return rs

    }

    

    public static void main(String[] args) {

        // JDBCUtilDemo jd = new JDBCUtilDemo()

        // System.out.println(jd.getConnection())

        // if(jd.updateByUserId("8888" )){

        // System.out.println("OK")

        // }else{

        // System.out.println("NO")

        // }

    }

}

其实,也就那几步而已:

别忘了,加载jar文件

加载驱动

获得Connection

获得PreparedStatement /PreparedStatement

执行sql语句

处理结果集ResultSet

关闭连接

mport java.sql.Connection

import java.sql.PreparedStatement

import java.sql.ResultSet

import java.util.ArrayList

import java.util.List

import Entity.JIAJU

public class JiaJu {

 public JIAJU selectExe(int shouhinId) {

  JIAJU jia = new JIAJU()

  try {

   Connection con = ConnectionManager.getConnection()

   String sql = "select * from jiaju where shouhinId=?"

   PreparedStatement ps = con.prepareStatement(sql)

   ps.setInt(1, shouhinId)

   ResultSet rs = ps.executeQuery()

   if (rs != null) {

    while (rs.next()) {

     jia.setShouhinId(rs.getInt("shouhinId"))

     jia.setShouhinName(rs.getString("shouhinName"))

     jia.setShouhinColor(rs.getString("shouhinColor"))

     jia.setShouhinPrice(rs.getInt("shouhinPrice"))

     jia.setShouhinPai(rs.getString("shouhinPai"))

     jia.setShouhinShi(rs.getString("shouhinShi"))

     // list.add(jia)

    }

   }

  } catch (Exception e) {

   e.printStackTrace()

  }

  return jia

 }

 public void insertJia(JIAJU jia) {

  try {

   Connection con = ConnectionManager.getConnection()

   String sql = "insert into jiaju values(?,?,?,?,?)"

   PreparedStatement ps = con.prepareStatement(sql)

   ps.setString(1, jia.getShouhinName())

   ps.setString(2, jia.getShouhinColor())

   ps.setInt(3, jia.getShouhinPrice())

   ps.setString(4, jia.getShouhinPai())

   ps.setString(5, jia.getShouhinShi())

   ps.executeUpdate()

  } catch (Exception e) {

   e.printStackTrace()

  }

 }

 public List selectJia() {

  List list = new ArrayList()

  

  try {

   Connection con = ConnectionManager.getConnection()

   String sql = "select * from jiaju "

   PreparedStatement ps = con.prepareStatement(sql)

   ResultSet rs = ps.executeQuery()

   if (rs != null) {

    while (rs.next()) {

     JIAJU jia = new JIAJU()

     jia.setShouhinId(rs.getInt("shouhinId"))

     jia.setShouhinName(rs.getString("shouhinName"))

     jia.setShouhinColor(rs.getString("shouhinColor"))

     jia.setShouhinPrice(rs.getInt("shouhinPrice"))

     jia.setShouhinPai(rs.getString("shouhinPai"))

     jia.setShouhinShi(rs.getString("shouhinShi"))

        list.add(jia)

    }

   }

  } catch (Exception e) {

   e.printStackTrace()

  }

  return list

 }

 public JIAJU selectbuy(int shouhinId) {

  JIAJU jia = new JIAJU()

  try {

   Connection con = ConnectionManager.getConnection()

   String sql = "select * from jiaju where shouhinId=?"

   PreparedStatement ps = con.prepareStatement(sql)

   ps.setInt(1, shouhinId)

   ResultSet rs = ps.executeQuery()

   if (rs != null) {

    while (rs.next()) {

     jia.setShouhinId(rs.getInt("shouhinId"))

     jia.setShouhinName(rs.getString("shouhinName"))

     jia.setShouhinColor(rs.getString("shouhinColor"))

     jia.setShouhinPrice(rs.getInt("shouhinPrice"))

     jia.setShouhinPai(rs.getString("shouhinPai"))

     jia.setShouhinShi(rs.getString("shouhinShi"))

    }

   }

  } catch (Exception e) {

   e.printStackTrace()

  }

  return jia

 }

  public void updateLou(JIAJU jia){

   try{

    Connection con = ConnectionManager.getConnection()

   String sql = "update jiaju set shouhinPrice=? where  shouhinId=?"

   PreparedStatement ps = con.prepareStatement(sql)  

   ps.setInt(1,jia.getShouhinPrice())

   ps.setInt(2, jia.getShouhinId())

   ps.executeUpdate()

   }catch(Exception e){

    e.printStackTrace()

   }

  }

  public void deleteLou(JIAJU jia){

   try{

    Connection con = ConnectionManager.getConnection()

   String sql = "delete from jiaju where shouhinId=?"

   PreparedStatement ps = con.prepareStatement(sql)

   ps.setInt(1, jia.getShouhinId())

   ps.executeUpdate()

   }catch(Exception e){

    e.printStackTrace()

   }

  }

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11752183.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存