MySql simple operation
<code>//启动mysql net start mysql //登陆 mysql -u root -p //创建建数据库 create database mydb; create database test; //删除数据库 drop database test; //使用数据库 use mydb; //创建表 create table mytable(name varchar(20),sex char); //显示数据库中所有表 show tables; //增加一列 alter table mytable add age int; //插入 insert mytable value("liu",'f',22); insert mytable value("wang",'m',22); insert mytable(name,sex) value("li",'f'); insert mytable value("zhao",'m',22); //删除表中项 delete from mytable where name=”liu“; delete from mytable where name=”li“; //更新 update mytable set age = 23 where name = "wang"; //查询 select * from mytable; </code>
JDBC
JDBC driver is divided into 4 categories
JDBC-ODBC bridge part local API, part Java driver JDBC network pure Java driver Program local protocol Java driver
JDBC example
<code>import java.sql.*; import com.mysql.jdbc.Driver; public class JDBCMySql { public void operateMySql() throws SQLException, ClassNotFoundException{ String driverName ="com.mysql.jdbc.Driver"; String URL = "jdbc:mysql://127.0.0.1:3306/mydb"; String sql = "SELECT * FROM mydb.mytable"; String username = "root"; String password = ""; Connection conn = null; try{ //加载驱动 Driver.class.forName(driverName); //建立连接 conn = DriverManager.getConnection(URL,username,password); //创建statement来执行sql语句 Statement ps = conn.createStatement(); //结果集处理 ResultSet rs = ps.executeQuery(sql); while(rs.next()) { System.out.println(rs.getString("name")+","+rs.getString("sex")+","+rs.getInt("age")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch(SQLException e){ e.printStackTrace(); } //关闭连接 finally{ if(conn!=null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }</code>
Create a test case to verify
<code> import static org.junit.Assert.*; import java.sql.SQLException; import org.junit.Before; import org.junit.Test; public class JDBCTest { @Test public void test() throws ClassNotFoundException, SQLException { JDBCMySql jm = new JDBCMySql(); jm.operateMySql(); } }</code>
Execution results
The above is the detailed content of Detailed explanation of the simple use of MySQL and sharing of JDBC sample code. For more information, please follow other related articles on the PHP Chinese website!