JAVA uses JDBC technology to operate SqlServer databases.

Source: Internet
Author: User

JAVA uses JDBC technology to operate SqlServer databases.

JDBC (Java Data Base Connectivity, Java database connection) is a Java API used to execute SQL statements. It can provide unified access to multiple relational databases, it consists of a group of classes and interfaces written in Java. JDBC provides a benchmark to build more advanced tools and interfaces so that database developers can write database applications. JDBC does not directly access the database. You need to use the JDBC driver provided by the database vendor.

Database Connection
To access the database in Java, first load a database driver. The database driver only needs to be loaded once during the first access. Then, a Connection instance is created every time you access the database to obtain the database Connection. This allows you to execute SQL statements that operate the database. The database connection is released after use.
Database driver
Different databases implement different JDBC interfaces, so different database driver packages are generated. The driver package contains some classes responsible for database connection, and passes the SQL statements that we want to operate. My PC uses SQL2012, so we are going to http://www.microsoft.com/zh-cn/search/DownloadResults.aspx here? Q = jdbc download driver

Import the driver package to the newly created java_project.

Right-click the selected project> Build Path> Add External Archives... select the file to download and decompress

Project after successful import:

Package com. project_DataBase01; import java. SQL. connection; import java. SQL. driverManager; public class SelectQuery {private Connection conn;/** create a method for returning Connection */public Connection getConnection () {try {Class. forName ("com. microsoft. sqlserver. jdbc. SQLServerDriver "); System. out. println ("database driver loaded successfully"); conn = DriverManager. getConnection ("jdbc: sqlserver: // localhost: 1433; DatabaseName = java_conn_test", "sa", "123456"); if (conn = null) {System. out. println ("database connection failed"); System. out. println ("-----------------------");} else {System. out. println ("database connection successful"); System. out. println ("-----------------------") ;}} catch (Exception e) {// TODO: handle exception e. printStackTrace () ;}return conn ;}}

In the SqlServe database java_conn_test, tb_User adds, deletes, modifies, and queries data.

Package com. project_DataBase01; import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. statement; public class StartMain {private static Connection conn; public static void main (String [] args) {// TODO Auto-generated method stub conn = new SelectQuery (). getConnection (); GetInsert (); GetSelect (); GetUpdate (); GetSelect (); GetDelete (); GetSelect ();}/** INSERT */public static void GetInsert () {if (conn! = Null) {// INSERT System. out. println ("----------- INSERT ------------"); int x = 1 + (int) (Math. random () * 5000); String insert_str = "insert into tb_User (UserName, UserPwd, UserId) VALUES ('name _" + x + "', 'pwd _ "+ x +" ', NEWID () "; try {Statement insertstatement = conn. createStatement (); int result = insertstatement.exe cuteUpdate (insert_str); if (result> 0) {System. out. println ("successfully added"); System. out. println ("-------------- --------- ");} Else {System. out. println ("failed to add"); System. out. println ("-----------------------") ;}} catch (Exception e) {System. out. println ("failed to add"); System. out. println ("-----------------------"); // TODO: handle exception} else {System. out. println ("Check database connection"); System. out. println ("-----------------------") ;}}/** SELECT */public static void GetSelect () {if (conn! = Null) {// SELECT System. out. println ("----------- SELECT ------------"); String select_str = "SELECT * FROM tb_User"; try {PreparedStatement selectps = conn. prepareStatement (select_str); ResultSet rs1_selectps.exe cuteQuery (); while (rs. next () {String name = rs. getString ("UserName"); String pwd = rs. getString ("UserPwd"); String UserId = rs. getString ("UserId"); System. out. println (name + "\ t" + pwd + "\ t" + UserId );} System. out. println ("query successful"); System. out. println ("-----------------------");} catch (Exception e) {// TODO: handle exception System. out. println ("query failed"); System. out. println ("-----------------------") ;}} else {System. out. println ("Check database connection"); System. out. println ("-----------------------") ;}}/** UPDATE */public static void GetUpdate () {if (conn! = Null) {// UPDATE System. out. println ("----------- INSERT ------------"); String update_str = "UPDATE tb_User SET UserPwd = UserPwd + 'xxxxxx' WHERE UserId = 'fa562573-hangzhou'"; try {Statement updatestatement = conn. createStatement (); int result=updatestatement.exe cuteUpdate (update_str); if (result> 0) {System. out. println ("modified successfully! "); System. out. println ("-----------------------");} else {System. out. println ("failed to modify"); System. out. println ("-----------------------") ;}} catch (Exception e) {// TODO: handle exception System. out. println ("failed to modify"); System. out. println ("-----------------------") ;}} else {System. out. println ("Check database connection"); System. out. println ("-----------------------") ;}}/** DELETE */public static void GetDelete (){ If (conn! = Null) {// DELETE System. out. println ("----------- DELETE ------------"); String delete_str = "DELETE tb_User WHERE UserId! = 'Fa562573-218a-4205-b67d-ebdfac3f8329 '"; try {Statement deletestatement = conn. createStatement (); int result==deletestatement.exe cuteUpdate (delete_str); if (result> 0) {System. out. println ("deleted successfully! "); System. out. println ("-----------------------");} else {System. out. println ("failed to delete"); System. out. println ("-----------------------") ;}} catch (Exception e) {// TODO: handle exception System. out. println ("failed to delete"); System. out. println ("-----------------------") ;}} else {System. out. println ("Check database connection"); System. out. println ("-----------------------");}}}

Run the program:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.