package NEW;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Database {
public static void main(String[] args) throws SQLException {
Database data=new Database();
data.search();
System.out.println("連接配接成功");
}
public static Connection getConn() throws SQLException {
//連接配接類,得到和目标資料庫連接配接的對象
Connection con=null;
//加載驅動
try {
Class.forName("com.mysql.jdbc.Driver");
//加載驅動類
con = DriverManager.getConnection("jdbc:mysql://localhost/stu",
"root", "123");
//擷取與目标資料庫的連接配接,參數("jdbc:mysql://localhost/資料庫名","root","資料庫密碼";
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static void search() throws SQLException
{
Connection con=getConn();//與目标資料庫連接配接的對象
ResultSet set=null;
PreparedStatement prepar=con.prepareStatement("select *from student");
//把sql語句發送到資料庫,得到預編譯類的對象,這句話是選擇該student表裡的所有資料
set=prepar.executeQuery();
//将得到的資料庫響應的查詢結果存放在ResultSet對象中
while(set.next())
{
System.out.print(set.getString("id"));//輸出對應表内容,“表的列名”
System.out.print(" "+set.getString("name"));
System.out.println(" "+set.getString("age"));
}
}
}
上面顯示了連接配接和擷取資料庫内容的方法;
下面是在cmd裡對資料庫的一些操作,暫時隻用了這些,以後學别的再來更新
show databases;展示所有的資料庫
use 資料庫名;使用資料庫,可以做修改
show tables;展示目前庫所有的表名
describe 表名;展示目前表裡的表頭
select *from 表名;展示所有的資訊
select user,host from mysql.user;使用者名
在資料庫裡添加表
creat table student(
id int NOT NULL auto_increment,
name vachar(200),
age vachar(200),
primary key(id)
);
insert into 表名 values('','','');插入
選擇:select * from table1 where 範圍
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 範圍