本文共 2213 字,大约阅读时间需要 7 分钟。
常用命令:
- create database 数据库名称
-
- use 数据库名称
-
- create table 表名 (name varchar(20),sex char(1))
-
- select * from 表名
-
- insert into 表名 value('','');
-
- update 表名 set 要更改 where 条件;
-
- delete from 表名 where 条件;
- String url = "jdbc:mysql://localhost:3306/xinbo05";//mysql数据库url
- Class.forName("com.mysql.jdbc.Driver");
- String url="jdbc:jtds:sqlserver://localhost:1433/smcs"; //sql数据库url
- Class.forName("net.sourceforge.jtds.jdbc.Driver");
连接mysql例子:
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
-
- public class TestSql
- {
- private Connection conn = null;
- private PreparedStatement statement = null;
- String url = "jdbc:mysql://localhost:3306/xinbo05";//数据库url
- String user = "root";
- String password = "";
-
-
- void conSql()
- {
- try
- {
- Class.forName("com.mysql.jdbc.Driver");
- conn = DriverManager.getConnection(url, user, password);
- }
- catch (ClassNotFoundException e)
- {
- e.printStackTrace();
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
-
- }
-
-
- ResultSet selectSQL(String sql)
- {
- ResultSet rs = null;
- try
- {
- statement = conn.prepareStatement(sql);
- rs = statement.executeQuery(sql);
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
-
- return rs;
-
- }
-
-
- boolean insertSQL(String sql)
- {
- try
- {
- statement = conn.prepareStatement(sql);
- statement.executeUpdate(sql);
- return true;
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
- return false;
-
- }
-
-
- void printing(ResultSet rs)
- {
- try
- {
- while(rs.next())
- {
- System.out.println(rs.getString("isname") + "\t" + rs.getString("sex"));
- }
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
- }
-
- public static void main(String[] args)
- {
- TestSql ts = new TestSql();
- ts.conSql();
- System.out.println("连接成功");
- String select = "select * from xinbo";
- String insert = "insert into xinbo value('fanfan','m')";
- String update = "update xinbo set isname='xxx' sex= 's' where isname = 'fanfan'";
- String delete = "delete from xinbo where isname = 'xx'";
-
- if(ts.insertSQL(delete)==true)
- {
- ResultSet rs = ts.selectSQL(select);
- ts.printing(rs);
- }
-
- }
- }
本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1191860,如需转载请自行联系原作者