数据库系统是由数据库、数据库管理系统、应用系统、数据库管理员构成。java
数据库管理系统简称DBMS(Database Management System),包括数据库的定义、数据查询、数据维护等。JDBC(Java DataBase Connectivity,Java数据库链接,用于执行SQL语句的Java API(Application Programming Interface,应用程序设计接口))技术是链接数据库与应用程序的纽带。mysql
一、在链接数据库以前要先肯定电脑上是否安装MySQL,在命令行用键入net start查看。sql
二、在MySQL命令行用create database db_data;建立数据库db_data数据库
example1url
package MySQLx; import java.sql.Connection; import java.sql.DriverManager; public class GetConn { public Connection conn = null; public Connection getConnection(){ try{ Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动 String url = "jdbc:mysql://localhost:3306/db_data"; String user = "root"; String password = "1225"; conn = DriverManager.getConnection(url,user,password);//链接db_data数据库 if(conn!=null){ System.out.println("数据库链接成功"); } }catch(Exception e){ e.printStackTrace(); } return conn; } public static void main(String[] args){ GetConn getConn = new GetConn(); getConn.getConnection(); } }
example2spa
先使用数据库db建表mytable,如下程序要使用。命令行
数据库添加、删除、查询、模糊查询设计
package MySQLx; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class ExecuteSql { public static void main(String[] args){ try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/db"; String user = "root"; String password = "1225"; Connection connec = DriverManager.getConnection(url,user,password); Statement statement = connec.createStatement(); statement.execute("insert into mytable values ('Rose','f')"); statement.execute("insert into mytable values ('Jack','m')"); statement.execute("insert into mytable values ('John','m')"); statement.execute("insert into mytable values ('Sunny','f')"); System.out.println("添加数据的行数为: "+ statement.getUpdateCount()); /*int count = statement.executeUpdate("delete from mytable"); System.out.println("删除数据的行数为:"+count);*///数据所有删除 //int count = statement.executeUpdate("delete from mytable where sex='f'"); //System.out.println("删除数据的行数为:"+count); //查询 String sql = "select name from mytable where sex='f'"; ResultSet res = statement.executeQuery(sql); while(res.next()){ String name = res.getString("name"); System.out.println(""+name); } //模糊查询 ResultSet result1 = null; String sql2 = "SELECT * FROM mytable where name like 'Sunn_'"; PreparedStatement statement1 = connec.prepareStatement(sql2); result1 = statement1.executeQuery(); while(result1.next()){ String name = result1.getString("name"); System.out.println(""+name); } connec.close(); }catch(Exception e){ e.printStackTrace(); } } }