Tag Archives: sqlserver

SQL Server Deletes a table foreign key constraint Error [Solved]

  Create two tables tbltesta and tbltesb, and delete tbltesta


			create table dbo.TblTestA(
			Id					bigint			primary key identity(1, 1),
			name			varchar(20)     unique,
		    )
	
			create table dbo.TblTestB(
			Id					bigint			primary key identity(1, 1),
			TestAId				bigint			not null foreign key references 
			Status				varchar(1),
	     	)

Error reported: it is referenced by a foreign key constraint

Reason: other tables refer to the foreign key of this table

Solution:

1. Find the foreign key of this table referenced by other tables

exec sp_Helpconstraint ‘table name’;

2. Find the associated foreign key constraint table name

select name
from   sys.foreign_key_columns f join sys.objects o on f.constraint_object_id=o.object_id
where f.parent_object_id=object_ID (‘foreign key association table name ‘)

3. Delete the foreign key constraint

Alter table foreign key constraint table, Drop constraint name (constraint name found above)


4. Delete table (events can be added)

BEGIN TRY
    BEGIN TRANSACTION
        ALTER TABLE TblTestB DROP CONSTRAINT FK__TblTestB__TestAI__635CD8E4
        DROP TABLE dbo.TblTestA
    COMMIT TRANSACTION
        PRINT 'commit sucesss'
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
    PRINT 'rollback sucesss'
END CATCH

 

[Solved] Mybatis integrates PageHelper and uses sqlserver paging error

The environment uses mybatis plus, the paging plug-in: PageHelper 5.2.0, and the database uses sqlserver2012 or above

In fact, the paging plug-in is ultimately handled by the mybatis interceptor, so it is equivalent to the mybatis environment.

Using paging

 PageHelper.startPage(1,10); // Pagination
  orderMapper.list(); // Follow the execution

Then an error will be reported

SQL: SELECT  id,product_name,xxxx,xxxxx  FROM product_xxxx  OFFSET ?ROWS FETCH NEXT ?ROWS ONLY
### Cause: com.microsoft.sqlserver.jdbc.SQLServerException: “@P0”There is a grammatical error nearby.
; uncategorized SQLException; SQL state [S0001]; error code [102]; There is a syntax error near "@P0". ; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: There is a syntax error near "@P0".

Finally, after checking, it is found that the paging syntax offset and fetch used by PageHelper are sqlserver’s support for sorting.

Therefore, if you want to use this plug-in to page, you need to add sorting.

PageHelper.startPage(1,10,"xxxx sorted table field name, not attribute name");
orderMapper.list(); // Follow the execution

Or use the default sort field

PageHelper.startPage(1,10,"CURRENT_TIMESTAMP");
orderMapper.list(); //Follow up

How to Solve Linux connecte to the old version of SQL Server Error

Most methods of online search can’t help me
the errors are as follows:
the server selected protocol version tls10 is not accepted by client preferences [tls12]
in the root directory of Java (mine is 1.8), the jdk11 will find the security file under conf, and there is a java.security file under JRE/lib/security, The jdk.tls.disabledalgorithms configuration in this file will disable the tls1.0 version of the transport protocol. At this time, we need to close the protocol and delete tls1.0. Of course, deletion under this file is useless. Most posts on the Internet also say that it is impossible to change this file. Therefore, the following methods are used, Create a new empty file and paste it as follows:

jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, \
 DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
 include jdk.disabled.namedCurves```
Save it and run the java project:

```bash
-Djava.security.properties=xxx

The above parameters determine the location of the new file. At this time, the error can be solved.

springboot sqlserver druid reward: validateConnection false

The exception information is as follows:

java.sql.SQLException: validateConnection false
	at com.alibaba.druid.pool.DruidAbstractDataSource.validateConnection(DruidAbstractDataSource.java:1418)
	at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1733)
	at com.alibaba.druid.pool.DruidDataSource$CreateConnectionThread.run(DruidDataSource.java:2801)
Caused by: java.lang.NullPointerException: null
	at com.alibaba.druid.wall.WallProvider.checkInternal(WallProvider.java:707)
	at com.alibaba.druid.wall.WallProvider.check(WallProvider.java:584)
	at com.alibaba.druid.wall.WallFilter.checkInternal(WallFilter.java:826)
	at com.alibaba.druid.wall.WallFilter.check(WallFilter.java:821)
	at com.alibaba.druid.wall.WallFilter.statement_execute(WallFilter.java:454)
	at com.alibaba.druid.filter.FilterChainImpl.statement_execute(FilterChainImpl.java:3008)
	at com.alibaba.druid.filter.FilterAdapter.statement_execute(FilterAdapter.java:2484)
	at com.alibaba.druid.filter.FilterEventAdapter.statement_execute(FilterEventAdapter.java:188)
	at com.alibaba.druid.filter.FilterChainImpl.statement_execute(FilterChainImpl.java:3008)
	at com.alibaba.druid.proxy.jdbc.StatementProxyImpl.execute(StatementProxyImpl.java:147)
	at com.alibaba.druid.pool.vendor.MSSQLValidConnectionChecker.isValidConnection(MSSQLValidConnectionChecker.java:50)
	at com.alibaba.druid.pool.DruidAbstractDataSource.validateConnection(DruidAbstractDataSource.java:1398)

Follow this method: com.alibaba.druid.pool.druidabstractdatasource.validateconnection

result = validConnectionChecker.isValidConnection(conn, validationQuery, validationQueryTimeout);

Find the exception of this line of code and enter this method

Find the method of this implementation class (because it is SQL server)

public boolean isValidConnection(final Connection c, String validateQuery, int validationQueryTimeout) throws Exception {
        if (c.isClosed()) {
            return false;
        }

        Statement stmt = null;

        try {
            stmt = c.createStatement();
            if (validationQueryTimeout > 0) {
                stmt.setQueryTimeout(validationQueryTimeout);
            }
            stmt.execute(validateQuery);
            return true;
        } catch (SQLException e) {
            throw e;
        } finally {
            JdbcUtils.close(stmt);
        }
    }

Finally, it is found that the method parameter validatequery is null, so a null pointer is reported. Let’s go back and see why it is null

protected volatile String                          validationQuery                           = DEFAULT_VALIDATION_QUERY;

Class defines that validationquery is equal to default_ VALIDATION_ Query, and default_ VALIDATION_ Query initialization is defined as null. In fact, this parameter comes from the springboot configuration file

Add the following configuration in the springboot data source configuration file:

druid:
                        validation-query: SELECT 1

Just do it!

PS, data source configuration:

driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://IP:PORT;DatabaseName=database name
username: username
password: password
druid:
    validation-query: SELECT 1

The COMMIT TRANSACTION request has no corresponding BEGIN

Background

Error thrown when inserting data into SQL Server database using Python:

Cannot commit transaction: (3902,b'The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
DB-Lib error message 20018, severity 16:\nGeneral SQL Server error:Check messages from the SQL Server\n')

analysis

Well, there’s no reason. But a solution was found by accident.

solve

The error caused by the field type in sqlserver. The error I encountered is: one of the fields is set to date type. When inserting data, I report an error. Change the date type to varchar type, the problem is solved, and the data is inserted normally.

Summary

The varchar type may affect the data usage. Solve the problem first, and then solve the problem later. I think that inserting varchar data into the database is the most stable (personal experience).


Personal ability is limited, if there is a mistake welcome to correct!

12-web security — error injection based on SQL Server — and, convert, cast

We know that SQL Server is developed by Microsoft, a very good database, can accurately locate the error message, this is very developer friendly, especially for Web security workers, using SQL Server error information to effectively penetrate the target system test.
 
Id =1′ and 1=(@@version)–+;

When executing SQL statement, the database will treat the contents in parentheses of 1=(@@Version) statement as the number of int type. However, @@Version itself is a string of type NVARCHAR. SQL Server will fail to convert NCARCHAR into INIT type and report an error.
 
SQL Server error injection principle is the use of data type conversion error. The character type is converted into a number of characters, but the form of expression is still characters, resulting in the database can not identify the error, at the same time in the process of error will also show the SQL statement query information, such as the database version of the query information combined with the error information back to the page.
 
For example, you can construct a SQL statement by inputing an error query into all table names in the current database:

id=1' and 1=(select top 1 table_name from information_schema.tables)--+


Note that since the = sign precedes the parentheses and the SELECT statement produces more than one result, you need to combine the top statement to limit the result of the query to one, display the result to the Web page by error, and then use the top n statement to query the following table names.
 
 
You can also use the FOR XML PATH and the QUOTENAME statement to display the result as a single line to construct the SQL statement:

select quotename(table_name) from information_schema.tables for xml path('')

 
 
Select * from user where user = ‘user’;

select quotename(column_name) from information_schema.columns where table_name='users' for xml path('')

 
Select * from user where user name = ‘user’ and password = ‘user’;

select username,':',password,'|' from users for xml path('')

 
Usually, the page may not be able to display all the user names and passwords due to the number of characters displayed. Substring function can be used to display the query results in sections, starting from the first character and displaying 250 characters:

select substring((select username,':',password,'|' from users for xml path('')),1,250)

SQL Server databases use the Substring function in the same way as MySQL does.
 
 
Select * from users where user = ‘users’;

 
 

Error injection based on convert and cast functions.

The convert function takes the time to define a datatype (format) in the form of:

convert(data_type(length),data_to_be_converted,style)

Parameters to the convert function:
DATA_TYPE (LENGTH) : Indicates the defined data type, and LENGTH represents the optional length
Data_to_be_converted: time, that is, the value of the need to transform
Style: Represents the output format of the specified time/date
 
 
Convert function:

 
VARCHAR (20) represents the data type defined as VARCHAR with a length of 20, getdate is used to get the current time, 111 represents the time output in year/month/day (i.e. 2020/07/11) format.
 
An error occurs if the convert function converts the database name to an int (such as the SQL statement select convert (int, db_name(), 111)), and the name of the database is also exposed.
 
 
Error injection based on the convert function:

id=1' and 1=convert(int,db_name(),111) --+


For the above SQL statements, the convert function will be the second parameter db_name after () attempts to convert the result of the type int, but because the db_name () returns is nvarchar type, the result of the SQL server cannot converting nvarchar type specified int type, so the convert function will be an error prompt, at the same time will be the second parameter specifies the results of the query of SQL statement together with the error message came out
 
The cast function converts one data type to another. The cast function is a function that converts one data type to another.

cast(expression as data_type)

CAST Parameter Description:
Expression: Any valid SQL Server expression
As: is used to split two parameters. The parameter before as (expression) is the data to be processed, and the parameter after as (data_type) is the data type to be converted
DATA_TYPE: Data types supplied by the target system, including BIGINT and SQL_VARLANT, cannot use user-defined data types
 
The cast function is used as follows:

 
SQL> convert 123456 to int;
 
 
The cast function converts the database name to an int, and the cast function reveals the database name security.

 
 
 
Error injection based on CAST function:

id=1' and 1=cast(host_name() as int) --+


 
 
SQL> select table names from sysobjects; select table names from sysobjects; select table names from sysobjects;

select quotename(name) from sysobjects where xtype='u' for xml path('')


 
 
SQL> select column name from column name;

select quotename(name) from syscolumns where id=(select id from sysobjects where name='users' and xtype='u') for xml path('')


 
 
 
SQL> select * from users where user = ‘user’;

select substring((select username,':',password,'|' from users for xml path('')),1,250)


 
In addition to displaying the username and password piecemeal using the Substring function, you can also display the username and password sequentially using the exclusion method.
 

com.microsoft.sqlserver . jdbc.SQLServerException : invalid object name ‘XX’

Myeclipse error message:
Error: com. Microsoft. Essentially. JDBC. SQLServerException: object name ‘xx’ is invalid
Warning: SQL Error: 208, SQLState: S0002
 
Error behavior: HQL statements can run in sqlserver, but run in hibernate to report an error.
Solution: The Settings in the.hbm.xml file of the data table mapping are incorrect. The database name catalog=”eportal” should be added, and the schema name schema=” DBO “should also be added.
This is a new feature in sqlserver2005, in mysql can be omitted.

SQL 2005 remote connection error (provider: SQL network interface, error: 28 – the server does not support the requested protocol

Solution: On the server side: Open SQL2005 SQL Server Management Studio program
(1) to connect to the database,
(2) trying to choose the registered under the menu Server
if there are no things out of the window, to update the local Server database engine right click on the select register
(3) on the local hope remote access database, right click on the select SQL Server configuration manager
(4) in the window, Select SQL Server 2005 network configuration in the left tree, select the appropriate database in the sub-set,
(5) and right click on TCP/IP in the right protocol to enable it
I followed this method to do first, and then found that it was still unable to connect to the server, finally use the following method to solve: start — “program –” Microsoft SQL Server 2005–& GT; SQL Server 2005 Peripheral Application Configurator select “Peripheral Application Configurator for Services and Connections” in this SQL server instance select Database Engine -& GT; For remote connections, select both TCP/IP and Named Pipes in the box on the right for local and remote connections