Java writes programs to create databases and tables

一个新手
Release: 2017-10-13 10:13:12
Original
1653 people have browsed it

The example in this article can be seen. It mainly uses Java to operate SQL statements. The principle is the same as ordinary addition, deletion, modification and query:


##

import java.sql.*; public class Test { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); //一开始必须填一个已经存在的数据库 String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"; Connection conn = DriverManager.getConnection(url, "root", "123456"); Statement stat = conn.createStatement(); //创建数据库hello stat.executeUpdate("create database hello"); //打开创建的数据库 stat.close(); conn.close(); url = "jdbc:mysql://localhost:3306/hello?useUnicode=true&characterEncoding=utf-8"; conn = DriverManager.getConnection(url, "root", "123456"); stat = conn.createStatement(); //创建表test stat.executeUpdate("create table test(id int, name varchar(80))"); //添加数据 stat.executeUpdate("insert into test values(1, '张三')"); stat.executeUpdate("insert into test values(2, '李四')"); //查询数据 ResultSet result = stat.executeQuery("select * from test"); while (result.next()) { System.out.println(result.getInt("id") + " " + result.getString("name")); } //关闭数据库 result.close(); stat.close(); conn.close(); } }
Copy after login

The above is the detailed content of Java writes programs to create databases and tables. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!