java数据库基础(mysql)1

本文通过一个Java类演示了如何使用标准SQL语句与数据库进行交互,包括插入数据、查询数据等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.xasmall.sql;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;  

public class Demo1 {  
    public static final String url = "jdbc:mysql://127.0.0.1/user";  
    public static final String name = "com.mysql.jdbc.Driver";  
    public static final String user = "root";  
    public static final String password = "root";  
    public static Connection conn=null;
    public Demo1() throws ClassNotFoundException, SQLException {
        Class.forName(name);
        conn=DriverManager.getConnection(url,user,password);
    }
    //Statement
    public void exe1() throws SQLException {
        Statement con=conn.createStatement();
        String sql="insert into student values('37932747','张元')";
//      String id="16281137";
//      String name="张元";
//      String sql="insert into student values('"+id+"','"+name+"')";
        con.execute(sql);
        con.close();
    }
    //PreparedStatement
    public void exe2() throws SQLException {
        String sql="Select *from student";
        PreparedStatement ps=conn.prepareStatement(sql);
        ResultSet rs=ps.executeQuery();
        System.out.println("id"+"--------"+"name");
        while(rs.next()){
            System.out.println(rs.getString(1)+"----"+rs.getString(2));
        }
        ps.close();
    }
    //占位符
    public void exe3() throws SQLException {
        String sql="insert into student(id,name) values(?,?)";
        PreparedStatement ps=conn.prepareStatement(sql);
        ps.setObject(1, "379181930");
        ps.setObject(2, "原子");
        ps.execute();
        ps.close();
    }
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Demo1 test1=new Demo1();
        test1.exe1();
        test1.exe2();
        test1.exe3();
    }
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值