怎么用java向数据库中添加和删除数据

2024-12-20 19:22:58
推荐回答(5个)
回答1:

我这有个类,一直用

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 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 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 
     * @param sql
     * @param params
     * @param t
     * @return
     */

    public static  List qureyAll(String sql, List params,
            Class t) {
        // 用一个集合接受返回的数据
        List list = new ArrayList();

        // 判断是否连接
        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");
        // }

    }

}

回答2:

java和数据库之间只能通过传值过程对数据库进行操作,dao可以实现,但最终还是会用到数据库语句。

回答3:

首先,下载连接access的驱动jar包;
然后把这个jar包拖到Eclipse项目中的lib文件夹下;
接着在src文件夹下新建一个package,然后写一个数据库的类;
关键代码:
String driver = "......";
String url = ".....";
String user= "...";
String password="...";
try{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url);
}catch(Exception e){}
Statement stmt = null;
//查
String sql = "select * from aaa";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);

//增
String sql = "insert into aaa values('a','b','c')";
stmt.execute(sql);

//改
String sql = "update aaa set name='b' where name='a'";
stmt.executeUpdate(sql);

//删
String sql = "delete from aaa where name = 'b'";
stmt.execute(sql);

反正就是类似这样的啦

回答4:

Access 做过。不过还是建议你去学下JDBC,学完自然就会了。先用Windows的ODBC建一个到Access的访问。然后用Java连接ODBC.

回答5:

用JDBC配置数据库链接,编写后台SQL代码