您的位置:首页 > 编程语言 > Java开发

Java向mysql中插入数据

2016-04-16 20:58 330 查看
一、向数据库中插入少数数据

package jdbc1;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import com.mysql.jdbc.PreparedStatement;

public class j1

{

public static void main(String[] args)

{

String driver = "com.mysql.jdbc.Driver";  

//localhost指本机,也可以用本地ip地址代替,3306为MySQL数据库的默认端口号,“user”为要连接的数据库名

String url = "jdbc:mysql://localhost:3306/user";

String username = "root"; //数据库的用户名

String password = "123456"; //密码

String sql2="insert into test2 values(100,200,300)"; //要插入的数据

try

{

Class.forName(driver);//加载驱动程序,此处运用隐式注册驱动程序的方法

}

catch(ClassNotFoundException e)

{

e.printStackTrace();

}

try

{

Connection con = DriverManager.getConnection(url,username,password);//创建连接对象

Statement st2 = con.createStatement();//创建sql执行对象

st2.executeUpdate(sql2);

}

}

二、要插入大量数据时,可以使用带占位符(?)参数的SQL语句来实现

创建一个PreparedStatement对象

pstmt=con.prepareStatement("insert into test2 values(?,?,?)")

示例代码如下:

package jdbc1;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

import java.sql.PreparedStatement;

import java.sql.Statement;

//import com.mysql.jdbc.PreparedStatement;

public class j1

{

public static void main(String[] args)

{

String driver = "com.mysql.jdbc.Driver";  

//localhost指本机,也可以用本地ip地址代替,3306为MySQL数据库的默认端口号,“user”为要连接的数据库名

String url = "jdbc:mysql://localhost:3306/user";

String username = "root"; //数据库的用户名

String password = "123456"; //密码

Scanner s=new Scanner(System.in);  //插入由键盘录入的值

System.out.println("s1:");

String s1=s.next();

System.out.println("s2:");

String s2=s.next();

System.out.println("s3:");

String s3=s.next();

try

{

Class.forName(driver);//加载驱动程序,此处运用隐式注册驱动程序的方法

}

catch(ClassNotFoundException e)

{

e.printStackTrace();

}

try

{

Connection con = DriverManager.getConnection(url,username,password);//创建连接对象

Statement st2 = con.createStatement();//创建sql执行对象

PreparedStatement pstmt=con.prepareStatement("insert into test2 values(?,?,?)");

{
pstmt.setString(1, s1);
pstmt.setString(2, s2);
pstmt.setString(3, s3);
pstmt.executeUpdate();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: