标签:
不多说,直接上代码。百度上面也是一大堆,大家多问百度就行。
在利用JDBC访问数据库过程中,主要涉及三种资源:对数据库的连接的连接对象Connection,SQL语句对象 Statement,访问结果集ResultSet 或 RowSet。
package ShopCar; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCTest { public static void main(String[] args) { //驱动程序 String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://127.0.0.1:3306/db"; String user = "root"; String password = ""; try { Class.forName(driver);//加载驱动 Connection conn = DriverManager.getConnection(url,user,password); // 连接URL为 jdbc:mysql://服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码 System.out.println("Success connect Mysql server!"); // statement用来执行SQL语句 Statement stmt = conn.createStatement(); // 结果集 ResultSet rs = stmt.executeQuery("select * from `student`"); // student 为你表的名称 while (rs.next()) { System.out.println(rs.getString("Sno")); } } catch (Exception e) { // TODO: handle exception System.out.print("get data error!"); e.printStackTrace(); } } }
如何向数据库中插入数据
import java.sql.*; publicclass Myjproject { publicstaticvoid main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序 //Class.forName("org.gjt.mm.mysql.Driver"); System.out.println("Success loading Mysql Driver!"); } catch (Exception e) { System.out.print("Error loading Mysql Driver!"); e.printStackTrace(); } try { Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test","root","123456"); int num=100; PreparedStatement Statement=connect.prepareStatement("INSERT INTO user VALUES(?,?)"); for(int i=0;i<num;i++) //定义个100次的循环,往表里插入一百条信息。 { Statement.setString(1,"chongshi"+i); Statement.setString(2,"bo"+i); Statement.executeUpdate(); } // } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // System.out.println("An error has occurred:"+e.toString()); // e.printStackTrace(); }catch(SQLException e) { } } }
标签:
原文地址:http://www.cnblogs.com/xs-yqz/p/4889176.html