search
HomeBackend DevelopmentPHP TutorialPHP随手笔记整理之PHP脚本和JAVA连接mysql数据库_PHP

环境

开发包:appserv-win32-2.5.10

服务器:Apache2.2

数据库:phpMyAdmin

语言:php5,java

平台:windows 10

java驱动:mysql-connector-java-5.1.37

需求

编写一个PHP脚本语言,连接到phpMyAdmin数据库的test库

编写一个java web服务端,连接到phpMyAdmin数据库的test库

代码

php连接方式

mysql.php

<&#63;php
/*****************************
*数据库连接
*****************************/
$conn = @mysql_connect("localhost","root","123");
if (!$conn){
  die("连接数据库失败:" . mysql_error());
}
mysql_select_db("test", $conn);
//字符转换,读库
mysql_query("set character set utf8");
mysql_query("set names utf8");
&#63;>

test.php测试

<&#63;php 
  error_reporting(0);     //防止报错
  include('mysql.php');
  $result=mysql_query("select * from user"); //根据前面的计算出开始的记录和记录数
  // 循环取出记录
  $six;
  while($row=mysql_fetch_row($result))
  {  
  echo $row[0];
  echo $row[1];
  }
&#63;>

 运行截图 :

java 连接方式

1.新建一个java project为mysqlTest

2.加载JDBC驱动,mysql-connector-java-5.1.37

MySQLConnection.java

package com.mysqltest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/*
 * **Mysql连接**
 * 
 * 参数:
 * conn 连接
 * url mysql数据库连接地址
 * user 数据库登陆账号
 * password 数据库登陆密码
 * 方法:
 * conn 获取连接
 */
public class MySQLConnection {
  public static Connection conn = null;
  public static String driver = "com.mysql.jdbc.Driver";
  public static String url = "jdbc:mysql://127.0.0.1:3306/post";
  public static String user = "root";
  public static String password = "123";
  /*
   * 创建Mysql数据连接 第一步:加载驱动 Class.forName(Driver) 第二步:创建连接
   * DriverManager.getConnection(url, user, password);
   */
  public Connection conn() {
    try {
      Class.forName(driver);
    } catch (ClassNotFoundException e) {
      System.out.println("驱动加载错误");
      e.printStackTrace();
    }
    try {
      conn = DriverManager.getConnection(url, user, password);
    } catch (SQLException e) {
      System.out.println("数据库链接错误");
      e.printStackTrace();
    }
    return conn;
  }
}

Work.java

package com.mysqltest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
 * mysql增删改查
 */
public class Work {
  /*
   * insert 增加
   */
  public static int insert() {
    MySQLConnection connection = new MySQLConnection();
    Connection conns; // 获取连接
    PreparedStatement pst; // 执行Sql语句
    int i = 0;
    String sql = "insert into user (username,password) values(&#63;,&#63;)";
    try {
      conns = connection.conn();
      pst = conns.prepareStatement(sql);
      pst.setString(1, "lizi");
      pst.setString(2, "123");
      i = pst.executeUpdate();
      pst.close();
      conns.close();
    } catch (SQLException e) {
      System.out.println("数据写入失败");
      e.printStackTrace();
    }
    return i;
  }
  /*
   * select 写入
   */
  public static void select() {
    MySQLConnection connection = new MySQLConnection();
    Connection conns; // 获取连接
    PreparedStatement pst; // 执行Sql语句(Statement)
    ResultSet rs; // 获取返回结果
    String sql = "select * from user";
    try {
      conns = connection.conn();
      pst = conns.prepareStatement(sql);
      rs = pst.executeQuery(sql);// 执行sql语句
      System.out.println("---------------------------------------");
      System.out.println("名字    |    密码");
      while (rs.next()) {
        System.out.println(rs.getString("username") + "    |    " + rs.getString("password"));
      }
      System.out.println("---------------------------------------");
      conns.close();
      pst.close();
      rs.close();
    } catch (SQLException e) {
      System.out.println("数据查询失败");
      e.printStackTrace();
    }
  }
  /*
   * update 修改
   */
  public static int update() {
    MySQLConnection connection = new MySQLConnection();
    Connection conns; // 获取连接
    PreparedStatement pst; // 执行Sql语句(Statement)
    int i = 0;
    String sql = "update user set password = &#63; where username = &#63;";
    try {
      conns = connection.conn();
      pst = conns.prepareStatement(sql);
      pst.setString(1, "123");
      pst.setString(2, "lizi");
      i = pst.executeUpdate();
      pst.close();
      conns.close();
    } catch (SQLException e) {
      System.out.println("数据修改失败");
      e.printStackTrace();
    }
    return i;
  }
  /*
   * delete 删除
   */
  public static int delete() {
    MySQLConnection connection = new MySQLConnection();
    Connection conns; // 获取连接
    PreparedStatement pst; // 执行Sql语句(Statement)
    int i = 0;
    String sql = "delete from user where username = &#63;";
    try {
      conns = connection.conn();
      pst = conns.prepareStatement(sql);
      pst.setString(1, "lizi");
      i = pst.executeUpdate();
      pst.close();
      conns.close();
    } catch (SQLException e) {
      System.out.println("数据删除失败");
      e.printStackTrace();
    }
    return i;
  }
  /*
   * test
   */
  public static void main(String[] args) {
    // System.out.println(insert());
     select();
    // System.out.println(update());
    // System.out.println(delete());
  }
}

 test截图

ps:php操作MySQL数据库中语句

我们常常用conn.php文件来建立与数据库的链接,然后在所需的文件中利用include 进行调用。这样有效防止对数据库属性的改动 而引起其他有关文件对数据调用的错误。

  现在来看一个conn.php文件,代码如下:

<&#63;php
 $conn=@mysql_connect("localhost","root","")or die("数据库连接错误");//链接数据库服务器
 mysql_select_db("messageboard",$conn);//选择数据库名为messageboard
 mysql_query("set names 'utf'");//使用utf编码,这里不能写成utf-否则将显示乱码,但UTF不区分大小写
 &#63;>

学习积累,收集了PHP操作MYSQL的几个基础函数:

.使用mysql_connect()函数连接MySQL服务器:mysql_connect("hostname", "username","password");
如,$link = mysql_connect("localhost", "root", "") or die("不能连接到数据库服务器!可能是数据库服务器没有启动,或者用户名密码有误!".mysql_error());

.使用mysql_select_db()函数选择数据库文件:mysql_query("use 数据库名",$link);

如,$db_selected=mysql_query("use example",$link);

.使用mysql_query()函数执行SQL语句:mysql_query(string query(SQL语句),$link);

如:

添加会员:$result=mysql_query("insert into tb_member values('a','')",$link);

修改会员:$result=mysql_query("update tb_member setuser='b',pwd=''where user='a'",$link);

删除会员:$result=mysql_query("delecte from tb_member where user='b'",$link);

查询会员:$sql=mysql_query("select * from tb_book");

模糊查询:$sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");

//通用符%表示零个或任意多个字符。

显示表结构:$result=mysql_query("DESC tb_member");

.使用mysql_fetch_array()函数从数组结果集中获得信息:

语法结构:array mysql_fetch_array(resource result[,int result_type])

参数result资源类型的参数,整形型参数,要传入的是由mysql_fetch_array()函数返回的数据指针;

参数result_type:可选项,php操作MySQL数据库语句基础整数型参数,要传入的是MYSQL_ASSOC(关联索引)、MYSQL_NUM(数字索引) MYSQL_BOTH(包括前两者,默认值)

如:

<>$sql=mysql_query("select * from tb_book");
$info=mysql_fetch_object($sql);
<>$sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");
$info=mysql_fetch_object($sql);

.使用mysql_fetch_object()函数从结果集中获取一行作为对象:

语法结构:object mysql_fetch_object(resource result);

如:

<>$sql=mysql_query("select * from tb_book");
$info=mysql_fetch_object($sql);
<>$sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");
$info=mysql_fetch_object($sql);

mysql_fetch_object()函数与mysql_fetch_array()函数类似,只有一点区别,即返回一个对象而不是数组,该函数只能通过字段名来访问数组。访问结果集中行的元素的语法结构:$row->col_name(列名)

.使用mysql_fetch_row()函数逐行获得结果集中的每条记录:

语法结构:array mysql_fetch_row(resource result)

如:

<>$sql=mysql_query("select * from tb_book");
$row=mysql_fetch_row($sql);
<>$sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");
$row=mysql_fetch_row($sql);

.使用mysql_num_rows()函数获取结果集中地记录数:

语法结构:int mysql_num_rows(resource result)

如:

$sql=mysql_query("select * from tb_book");
......
<&#63;php $nums=mysql_num_rows($sql);echo $nums;&#63;>

注:若要获得insert、update、delete语句的所影响到的数据,则必须使用mysql_affected_rows()函数来实现。

.mysql_query("set names gb");//设置MySQL的编码格式为 gb类型,以屏蔽乱码。

.关闭记录集:mysql_free_result($sql);

.关闭MySQL数据库服务器:mysql_close($conn);

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor