欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java操作mysql入门代码实例(含插入、更新和查询)

程序员文章站 2023-11-07 19:00:28
复制代码 代码如下:import java.sql.*;public class mysql {    public static...

复制代码 代码如下:

import java.sql.*;

public class mysql {
    public static string url = "jdbc:mysql://localhost:3306/test";//characterencoding=gbk
    public static string username = "root";
    public static string password = "root";
    public static connection con;
    public static statement stmt;
    public static resultset rs;

    public static void main(string[] args) throws sqlexception {
        connect();
        operation();
        stmt.close();
        con.close();
    }
    public static void test() {
        string sql_select = "select * from tablename where id=1";
        string sql_insert = "insert into tablename (col1,col2..) values('1','2'...)";
        string sql_update = "update tablename set colname='update' where id=1";
        //insert(sql_insert);
        //select(sql_select);
        //update(sql_update);
    }
    public static void connect() {
        // 定位驱动
        try {
            class.forname("com.mysql.jdbc.driver");
            system.out.println("加载驱动成功!");
        } catch (classnotfoundexception e) {
            system.out.println("加载驱动失败!");
            e.printstacktrace();
        }
        // 建立连接
        try {
            con = drivermanager.getconnection(url, username, password);
            stmt = con.createstatement();
            system.out.println("数据库连接成功!");
        } catch(sqlexception e) {
            system.out.println("数据库连接失败!");
        }
    }
    public static void select(string sql) {
        try {
            rs = stmt.executequery(sql);
            resultsetmetadata meta_data = rs.getmetadata();//列名
            for (int i_col = 1; i_col <= meta_data.getcolumncount(); i_col++) {
                system.out.print(meta_data.getcolumnlabel(i_col) + "   ");
            }
            system.out.println();
            while (rs.next()) {
                for (int i_col = 1; i_col <= meta_data.getcolumncount(); i_col++) {
                    system.out.print(rs.getstring(i_col) + "  ");
                }
                system.out.println();
            }
            rs.close();
        }catch (exception e) {
            system.out.println("数据查询失败!");
        }
    }
    public static void insert(string sql) {
        try {
            stmt.clearbatch();
            stmt.addbatch(sql);
            stmt.executebatch();
            system.out.println("数据插入成功!");
        }catch (exception e) {
            system.out.println("数据插入失败!");
        }

    }
    public static void update(string sql) {
        try {
            stmt.executeupdate(sql);
            system.out.println("数据更新成功!");
        }catch (exception e) {
            system.out.println("数据更新失败!");
        }
    }
}