In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
java 调用mysql实例:
package com.tanglei.test1;
import java.sql.*;
public class Testsql{
public static void main(String []args){
Mysql mysql=new Mysql();
}
}
class Mysql{
// MySQL的JDBC URL编写方式:jdbc:mysql://主机名称:连接端口/数据库的名称?参数=值
// 避免中文乱码要指定useUnicode和characterEncoding
// 执行数据库操作之前要在数据库管理系统上创建一个数据库,名字自己定,
// 下面语句之前就要先创建javademo数据库
Connection cnn=null;
String sql;
String url="jdbc:mysql://localhost:3306/test?useSSL=false";
public Mysql(){
try{
// 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来,
// 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来
//1.添加驱动
Class.forName("com.mysql.jdbc.Driver");
//2.建立连接
// 一个Connection代表一个数据库连接
cnn=DriverManager.getConnection(url,"tester","pass1234");
cnn.setAutoCommit(false);
//3.创建statement
// Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等
Statement stmt=cnn.createStatement();
sql="create table if not exists student(No varchar(20),Name varchar(20),primary key(No))";
int res=stmt.executeUpdate(sql);
cnn.commit();
// System.out.println(res);
if(res!=-1){
System.out.println("数据库创建成功!");
sql="insert into student (No,Name)values ('S001','Ray')";
stmt.executeUpdate(sql);
sql="insert into student (No,Name)values ('S002','Swead')";
stmt.executeUpdate(sql);
sql="insert into student (No,Name)values ('S003','Deny')";
stmt.executeUpdate(sql);
sql="select * from student";
ResultSet rs=stmt.executeQuery(sql);
System.out.println("学号\t姓名");
while (rs.next()){
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
}
sql="drop table student";
stmt.executeUpdate(sql);
}
}catch(Exception e){
e.printStackTrace();
try{
cnn.rollback();
}catch (SQLException e1){
e1.printStackTrace();
}
}finally{
try{
cnn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.