我正在使用C#和.NET 3.5.我需要生成并存储一些T-SQL插入语句,稍后将在远程服务器上执行.
例如,我有一个Employees数组:
new Employee[]
{
new Employee { ID = 5, Name = "Frank Grimes" },
new Employee { ID = 6, Name = "Tim O'Reilly" }
}
Run Code Online (Sandbox Code Playgroud)
我需要最终得到一个字符串数组,如下所示:
"INSERT INTO Employees (id, name) VALUES (5, 'Frank Grimes')",
"INSERT INTO Employees (id, name) VALUES (6, 'Tim O''Reilly')"
Run Code Online (Sandbox Code Playgroud)
我正在看一些使用String.Format创建insert语句的代码,但这感觉不对.我考虑使用SqlCommand(希望做这样的事情),但它没有提供将命令文本与参数组合的方法.
仅仅替换单引号并构建字符串就足够了吗?
string.Format("INSERT INTO Employees (id, name) VALUES ({0}, '{1}')",
employee.ID,
replaceQuotes(employee.Name)
);
Run Code Online (Sandbox Code Playgroud)
这样做时我应该关注什么?源数据相当安全,但我不想做太多假设.
编辑:只是想指出在这种情况下,我没有SqlConnection或任何方式直接连接到SQL Server.这个特定的应用程序需要生成sql语句并将它们排队等待在其他地方执行 - 否则我将使用SqlCommand.Parameters.AddWithValue()
字符串是不可变的,这意味着,一旦创建它们就无法更改.
那么,这是否意味着如果你用+ =附加的东西比你创建一个StringBuffer并附加文本那么需要更多的内存?
如果你使用+ =,每次必须保存在内存中时你会创建一个新的'对象',不是吗?
我需要在循环中连续构建大字符串并将它们保存到数据库中,目前偶尔会产生一个OutOfMemoryException.
这里基本上是基于一些数据使用XmlWriterwith 创建一个字符串StringBuilder.然后我从外部库调用一个方法,将该xml字符串转换为其他字符串.之后,转换后的字符串将保存到数据库中.对于不同的数据,这整个过程在一个循环中重复完成大约100次.
字符串本身不是太大(每个低于500kByte),并且在此循环期间进程内存不会增加.但是,偶尔我会得到一个OutOfMemeoryExcpetion内部StringBuilder.Append.有趣的是,此异常不会导致崩溃.我可以捕获该异常并继续循环.
这里发生了什么?为什么我会得到一个OutOfMemoryException尽管系统中仍有足够的可用内存?这是一些GC堆问题吗?
鉴于我无法绕过转换所有这些字符串,我能做些什么来使这项工作可靠?我应该强制GC收集吗?应该Thread.Sleep进入循环?我应该停止使用StringBuilder吗?应该只是在面对时重试OutOfMemoryException?
感觉很脏.但也许它不是......使用StringBuilder编写XML是否可以?我的直觉说:"虽然这感觉不对,但它可能非常高效,因为它没有加载额外的库和开销,它没有做任何额外的方法调用XmlWriter调用." 它似乎只是一般的代码更少.XmlWriter有什么好处?
这是它的样子.我正在根据您来自的域构建OpenSearch XML文档.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/xml";
string domain = WebUtils.ReturnParsedSourceUrl(null); //returns something like www.sample.com
string cachedChan = context.Cache[domain + "_opensearchdescription"] as String;
if (cachedChan == null)
{
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.Append("<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\" xmlns:moz=\"http://www.mozilla.org/2006/browser/search/\">");
sb.Append(" <ShortName>Search</ShortName>");
sb.Append(" <Description>Use " + domain + " to search.</Description>");
sb.Append(" <Contact>contact@sample.com</Contact>");
sb.Append(" <Url type=\"text/html\" method=\"get\" template=\"http://" + domain + "/Search.aspx?q={searchTerms}\" />");
sb.Append(" <moz:SearchForm>http://" + domain + "/Search.aspx</moz:SearchForm>");
sb.Append(" <Image height=\"16\" width=\"16\" type=\"image/x-icon\">http://" …Run Code Online (Sandbox Code Playgroud) 是否有一个隐式方法将scala.collection.mutable.StringBuilder转换为java.lang.StringBuilder?
我正在使用一个Java库(JCommander),其中一个方法(usage)接受一个java.jang.StringBuilder参数.
我需要一种方法来读取StringBuilder变量中的ini文件的所有部分/键:
[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
...
private List<string> GetKeys(string iniFile, string category)
{
StringBuilder returnString = new StringBuilder(255);
GetPrivateProfileString(category, null, null, returnString, 32768, iniFile);
...
}
Run Code Online (Sandbox Code Playgroud)
在returnString中只是第一个键值!如何一次性获取所有内容并将其写入StringBuilder和List?
谢谢您的帮助!
招呼leon22
在我的应用程序中,我以JSON的形式从服务器获取数据.数据大约为1.5 MB.该应用程序可以工作,但有时它会在从服务器获取OutOfMemoryError的数据时崩溃.
这是我的方法:
private String sendPostRequest(String url, List<NameValuePair> params)
throws Exception {
String ret = null;
BufferedReader bufferedReader = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
bufferedReader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuilder stringBuilder = new StringBuilder("");
StringBuilder stringBuilder2;
String line = "";
//String LineSeparator = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
ret = stringBuilder.toString();
stringBuilder = null;
} …Run Code Online (Sandbox Code Playgroud) 我创建了一个StringBuilder长度"132370292",当我尝试使用ToString()它抛出的方法获取字符串OutOfMemoryException.
StringBuilder SB = new StringBuilder();
for(int i =0; i<=5000; i++)
{
SB.Append("Some Junk Data for testing. My Actual Data is created from different sources by Appending to the String Builder.");
}
try
{
string str = SB.ToString(); // Throws OOM mostly
Console.WriteLine("String Created Successfully");
}
catch(OutOfMemoryException ex)
{
StreamWriter sw = new StreamWriter(@"c:\memo.txt", true);
sw.Write(SB.ToString()); //Always writes to the file without any error
Console.WriteLine("Written to File Successfully");
}
Run Code Online (Sandbox Code Playgroud)
创建新字符串时OOM的原因是什么?为什么在写入文件时它不会抛出OOM?
机器详细信息:64位,Windows-7,2GB RAM,.NET 2.0版
我问的问题与StringBuilder和StringBuffer之间的差异有关, 但不一样.我想看看如果同时由两个线程修改StringBuilder会发生什么.
我写了以下课程:
public class ThreadTester
{
public static void main(String[] args) throws InterruptedException
{
Runnable threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
myThread.start();
for (int i = 0; i < 100; i++)
{
Thread.sleep(10);
StringContainer.addToSb("a");
}
System.out.println("1: " + StringContainer.getSb());
System.out.println("1 length: " + StringContainer.getSb().length());
}
}
public class MyRunnable implements Runnable
{
@Override
public void run()
{
for (int i = 0; i < 100; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e) …Run Code Online (Sandbox Code Playgroud) java stringbuilder multithreading synchronization stringbuffer
该类StringBuilder定义了四个构造函数,但它们都没有接受StringBuilder,但以下编译:
StringBuilder sb = new StringBuilder(new StringBuilder("Hello"));
Run Code Online (Sandbox Code Playgroud)
这是否意味着StringBuilder编译器在内部以某种方式将匿名对象转换为String?
stringbuilder ×10
c# ×5
java ×3
stringbuffer ×2
.net ×1
.net-2.0 ×1
android ×1
asp.net ×1
constructor ×1
immutability ×1
ini ×1
memory ×1
scala ×1
sql ×1
streamwriter ×1
string ×1
tostring ×1
xml ×1